﻿HDU 1710 Binary Tree Traversals(二叉树)-Ocrosoft

Binary Tree Traversals

Problem Description

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.

Input

The 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.

Output

For 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
```

Solution

```#include <iostream>
#include <cstdio>
using namespace std;
int tree1[1001],tree2[1001];
//tree1的位置，tree2的位置，树的节点数，是否主根节点
void dfs(int a,int b,int n,int flag)
{
if(n==1){cout<<tree1[a]<<" ";return;}//节点只有一个，是叶子节点，输出
else if(n<=0)return;//没有节点，返回
int i;
for(i=0;tree1[a]!=tree2[b+i];i++);//找到tree2中与tree1[a]相等的数
dfs(a+1,b,i,0);//搜索左子树
//tree1[a+1]是左子树的根节点，tree2[b]也是右子树的根节点
//i是左子树的节点个数
dfs(a+i+1,b+i+1,n-i-1,0);//搜索右子树
//tree2[a+i+1]是右子树的根节点，tree2[b+i+1]也是右子树的根节点
//n-i-1是左子树的节点个数
if(flag)cout<<tree1[a];//输出主根节点的时候不输出空格
else cout<<tree1[a]<<" ";//输出其他根节点的时候后跟空格
}
int main()
{
int n;
while(cin>>n)
{
for(int i=0; i<n; i++)cin>>tree1[i];
for(int i=0; i<n; i++)cin>>tree2[i];
dfs(0,0,n,1);
cout<<endl;
}
return 0;
}
```