二叉树的遍历

来源:互联网 发布:淘宝店如何寻找货源 编辑:程序博客网 时间:2024/06/18 15:27
给出一棵二叉树的中序和前序遍历,输出它的后序遍历。
Input
本题有多组数据,输入处理到文件结束。


每组数据的第一行包括一个整数n,表示这棵二叉树一共有n个节点。


接下来的一行每行包括n个整数,表示这棵树的中序遍历。


接下来的一行每行包括n个整数,表示这棵树的前序遍历。


3<= n <= 100


Output
每组输出包括一行,表示这棵树的后序遍历。
Sample Input
7
4 2 5 1 6 3 7
1 2 4 5 3 6 7
Sample Output

4 5 2 6 7 3 1 

在本样例中,先序遍历的第一个数1就是这棵树的根节点,1在中序遍历中左边有4,2,5右边有6,3,7,也就找到了1的左子树和右子树中包含哪些数,同理先序遍历的第二个数2就是左子树的根节点,放在中序遍历中也能确定它的左右子树,用一个递归来实现,递归函数的参数是建树的范围l,r

#include<cstdio>#include<algorithm>#include<vector>using namespace std;const int M = 105;int tail;vector<int> pre, in, post;void rec(int l, int r){//    printf("l=%d r=%d\n", l, r);    if(l>=r)        return;    int root = pre[tail++];    int m = distance(in.begin(), find(in.begin(), in.end(), root));//    printf("root=%d\n", root); //   printf("l=%d m=%d\n", l, m);    rec(l, m);//先建成左子树,这样只要把根节点依次放到post数组就是后序遍历的结果    rec(m+1, r);    post.push_back(root);//第一个进入post的是整个树的左下角的节点,最后一个进入的就是总的根节点}int main(){    int n, tmp;    while(~scanf("%d", &n))    {        pre.clear();        in.clear();        post.clear();        tail = 0;        for(int i=1;i<=n;i++)        {            scanf("%d", &tmp);            in.push_back(tmp);        }        for(int i=1;i<=n;i++)        {            scanf("%d", &tmp);            pre.push_back(tmp);        }        rec(0, pre.size());//此处不该用pre.size()-1否则最右边的节点无法加入        for(int i=0;i<n;i++)        {            printf("%d ", post[i]);        }        printf("\n");    }    return 0;}


原创粉丝点击