题目:
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
分析与解答:
1.二叉树有根结点,有两个子结点,而且子结点数据类型和根节点相同,因此我们用struct存储
2.根据题中给的数据建树,先序后序中序,知道任意两个就可以建树
这题是给了中序和先序,左根右,根左右
主要问题就是根据遍历的性质找根,然后递归建立左子树右子树
先序:1 2 4 7 3 5 8 9 6
中序:4 7 2 1 8 5 9 3 6
先序第一个1是根
所以从中序开始找,472应当是第一个根的左子树
对应先序的247,可知,如果把左子树从新看成二叉树,那他的根就是2
再继续找,把左子树找完了
右子树35896 根是3,然后继续找
总结一下思想:
先创一个结点,他的根直接知道就是先序第一个数,先认为他没有左右子结点(因为如果递归到最后一个子叶,他没有子结点)
找到根后,通过递归调用,填他的左子树的结点值右子树的结点值
输出的话如果后序,输出:左子树,右子树,根
这题是由于空格的原因,我把数存到数组里了
#include <iostream>
#include <cstdio>
#include <cstring>
#include<cstdlib>
#include <algorithm>
#define N 1000
using namespace std;struct TreeNote
{int ch; TreeNote * ltree;TreeNote * rtree;
};
TreeNote * CreatTree(int * preorder, int * inorder, int longth)
{TreeNote * sontree = new TreeNote;sontree-> ch = *preorder;sontree-> ltree = NULL;sontree-> rtree = NULL;if(longth == 0)return NULL;int index = 0;for(; index < longth; index++)if(inorder[index] == *preorder)break;sontree-> ltree = CreatTree(preorder+1, inorder, index);sontree-> rtree = CreatTree(preorder+index+1, inorder+index+1, longth-index-1);return sontree;
}
int a[1000];
int p=0;
void PostOrder(TreeNote * tone)
{if(tone){PostOrder(tone-> ltree);PostOrder(tone-> rtree);a[p++]=tone->ch;}
}int main()
{int preorder[N];int inorder[N];int t; while(cin>>t){p=0;memset(a,0,sizeof(a));for(int i=0;i<t;++i){cin>>preorder[i];}for(int i=0;i<t;++i){cin>>inorder[i];}TreeNote * tone = CreatTree(preorder, inorder, t);PostOrder(tone);for(int i=0;i<p;++i){if(i!=p-1) cout<<a[i]<<' ';else cout<<a[i];} putchar('\n');}return 0;
}