Binary Tree Traversals(二叉树的遍历)

A binary tree is a finite set of vertices that is either empty or consists of a root r and two disjoint binary trees called the left and right subtrees. There are three most important ways in which the vertices of a binary tree can be systematically traversed or ordered. They are preorder, inorder and postorder. Let T be a binary tree with root r and subtrees T1,T2.
In a preorder traversal of the vertices of T, we visit the root r followed by visiting the vertices of T1 in preorder, then the vertices of T2 in preorder.
In an inorder traversal of the vertices of T, we visit the vertices of T1 in inorder, then the root r, followed by the vertices of T2 in inorder.
In a postorder traversal of the vertices of T, we visit the vertices of T1 in postorder, then the vertices of T2 in postorder and finally we visit r.
Now you are given the preorder sequence and inorder sequence of a certain binary tree. Try to find out its postorder sequence.

在这里插入图片描述

InputThe input contains several test cases. The first line of each test case contains a single integer n (1<=n<=1000), the number of vertices of the binary tree. Followed by two lines, respectively indicating the preorder sequence and inorder sequence. You can assume they are always correspond to a exclusive binary tree.

OutputFor each test case print a single line specifying the corresponding postorder sequence.

Sample Input
9
1 2 4 7 3 5 8 9 6
4 7 2 1 8 5 9 3 6
Sample Output
7 4 2 8 9 5 6 3 1

给你一个前序遍历和中序遍历,要求后序。
可以由先序和中序的性质得到 : 先序的第一个借点肯定是当前子树的根借点, 那么在
中序中找到这个结点, 则这个结点左边的节点属于左子树, 右边的属于右子树。然后递归遍历就可以了

方法一

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int mn=1010;
int n,g,a[mn],b[mn],c[mn];
void xia(int he,int ta,int &md)
{
 int d=md;
 if(he==ta)
 {
  c[++g]=a[d];
  return ;
 }
 for(int i=he;i<=ta;i++)
 {
  if(b[i]==a[md])
  {
   if(he<=i-1&&md+1<=n) xia(he,i-1,++md);
   if(i+1<=ta&&md+1<=n) xia(i+1,ta,++md);
   break;
   } 
 }
 c[++g]=a[d];
 return ;
}
int main()
{
 while(~scanf("%d",&n))
 {
  for(int i=1;i<=n;i++)
  scanf("%d",&a[i]);
  for(int j=1;j<=n;j++)
  scanf("%d",&b[j]);
  g=0;
  int md=1;
  xia(1,n,md);
  for(int i=1;i<n;i++)
  printf("%d ",c[i]);
  printf("%d\n",c[n]);
 }
}

方法二

#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
const int mm=1e3+10;
int a[mm],b[mm];
int n;
void dfs(int x,int y,int root)
{
 int i;
 if(x>y) return ;
 for(i=x;i<=y;i++)
  if(a[root]==b[i])
    break;
 dfs(x,i-1,root+1);
 dfs(i+1,y,root+(i-x)+1);
 printf("%d%c",a[root],root==1?'\n':' ');
}
int main()
{
 while(~scanf("%d",&n))
 {
  for(int i=1;i<=n;i++)
  scanf("%d",&a[i]);
  for(int i=1;i<=n;i++)
  scanf("%d",&b[i]);
  dfs(1,n,1);
 }
} 
发布了12 篇原创文章 · 获赞 1 · 访问量 190

猜你喜欢

转载自blog.csdn.net/csx_zzh/article/details/105149151
今日推荐