由中根序列和后根序列重建二叉树

来源:互联网 发布:vb考试系统 编辑:程序博客网 时间:2024/06/11 15:45

http://dsalgo.openjudge.cn/binarytree/4/

总时间限制: 500ms 内存限制: 65535kB

描述
本题输入一棵二叉树的中根序列和后根序列,要求在内存中重建二叉树,最后输出这棵二叉树的前根序列。

用不同的整数来唯一标识二叉树的每一个结点,下面的二叉树

这里写图片描述

中根序列是9 5 32 67

后根序列9 32 67 5

前根序列5 9 67 32

输入

两行。第一行是二叉树的中根序列,第二行是后根序列。每个数字表示的结点之间用空格隔开。结点数字范围0~65535。暂不必考虑不合理的输入数据。

输出
一行。由输入中的中根序列和后根序列重建的二叉树的前根序列。每个数字表示的结点之间用空格隔开。

样例输入
9 5 32 67
9 32 67 5
样例输出
5 9 67 32

#include <iostream>using namespace std;#define MAX 63556int zhong[MAX];int hou[MAX];int find_root(int back, int rootn){//在后序中找到树中的左半边子树的root    // rootn是树的root    // back是树的右半边子树的节点个数    return hou[rootn-back-1];}void build_tree(int begin, int num, int root, int rootn){    //cout<<begin<<" "<<num<<" "<<root<<endl;    // begin: 子树前序和后序打头的序号,两者相同    // num:  子树的长度    // root: 子树的根    // rootn:  子树的根在后序当中的序号    cout<<root<<" ";    if (num<=1){return;}    int j=1;    int temp=begin;    while(zhong[temp]!=root){ temp++; j++;}    j--;    int r=num-1-j;    if (r<0) return;    // temp是中序当中的root位置    // j是root前面的个数    //r是剩下的个数    int a = find_root(r,rootn);    // 在后序中找到左半边的root=a    build_tree(begin,j,a,rootn-r-1);    // 对左半边的进行递归    if (r>0){        a= hou[rootn-1];        // 找到右半边的root        build_tree(temp+1,r,a,rootn-1);}       // 对右半边的进行递归}

这里写图片描述

int main(){    int i=0;    while(cin>>zhong[i++]){        if (cin.get()!=' ') break;    }    //cin是跳过“空白”的;但是cin完一个数之后,“光标”还是在“空白”前面,cin.get()可以取到这个空白*    i=0;    while(cin>>hou[i++]){        if (cin.get()!=' ') break;    }    // i等于数字的个数    build_tree(0,i,hou[i-1],i-1);    cout<<endl;        return 0;}
0 0