二叉树-已知前序中序求后序

<题目重现>HDU - 1710

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
<解决思路>

这是一道数据结构笔试考试的必考题目,但是使用程序如何实现?仿照递归遍历的方法进行构建,将后序遍历的顺序直接保存至数组中,这里用到distance,distance的返回值为查找值到起始索引的距离,有关distance的介绍见http://blog.csdn.net/lanzhihui_10086/article/details/41805503

这个题还有一个问题就是多组数据输入,每一组数据结束进入下一组时要清空原来的容器,当时因为这个WA好多次。

#include
#include
#include

using namespace std;

int pos,n;

vectorpre,in,post;

void rec(int l,int r){
    if(l>=r)return ;
    int root=pre[pos++];
    int mid=distance(in.begin(),find(in.begin(),in.end(),root));
    rec(l,mid);
    rec(mid+1,r);
    post.push_back(root);
}

void solve(){
    pos=0;
    rec(0,pre.size());
    for(int i=0;i>n){
        pre.clear();
        in.clear();
        post.clear();

        for(int i=0;i>k;
            pre.push_back(k);
        }

        for(int i=0;i>k;
            in.push_back(k);
        }

        solve();
    }
    return 0;
}


你可能感兴趣的:(数据结构)