您的位置:首页 > Web前端

剑指offer系列源码-重建二叉树

2014-12-04 16:27 459 查看
oj地址

</pre><p><pre name="code" class="html">题目1385:重建二叉树
时间限制:1 秒内存限制:32 兆特殊判题:否提交:3609解决:1091
题目描述:
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并输出它的后序遍历序列。

输入:
输入可能包含多个测试样例,对于每个测试案例,
输入的第一行为一个整数n(1<=n<=1000):代表二叉树的节点个数。
输入的第二行包括n个整数(其中每个元素a的范围为(1<=a<=1000)):代表二叉树的前序遍历序列。
输入的第三行包括n个整数(其中每个元素a的范围为(1<=a<=1000)):代表二叉树的中序遍历序列。
输出:
对应每个测试案例,输出一行:
如果题目中所给的前序和中序遍历序列能构成一棵二叉树,则输出n个整数,代表二叉树的后序遍历序列,每个元素后面都有空格。
如果题目中所给的前序和中序遍历序列不能构成一棵二叉树,则输出”No”。
样例输入:
8
1 2 4 7 3 5 6 8
4 7 2 1 5 3 8 6
8
1 2 4 7 3 5 6 8
4 1 2 7 5 3 8 6
样例输出:
7 4 2 5 8 6 3 1
No

#include<iostream>
#include<stdio.h>
using namespace std;

struct BinaryTreeNode{
int value;
BinaryTreeNode* left;
BinaryTreeNode* right;
};
BinaryTreeNode* constructCore(int* startPreorder,int* endPreorder,
int * startInorder,int* endInoder){
int rootValue = startPreorder[0];
BinaryTreeNode* root  = new BinaryTreeNode();
root->value = rootValue;
root->left=root->right=NULL;
if(startPreorder==endPreorder){//只有一个节点的情况
if(startInorder==endInoder&&*startPreorder==*startInorder){
return root;
}else{
throw "error";
}
}
int* rootInorder = startInorder;
//中序查找根节点
while(rootInorder<=endInoder&&*rootInorder!=rootValue){
++rootInorder;
}
if(rootInorder==endInoder&&*rootInorder!=rootValue){
throw "error";
}
int leftLength = rootInorder-startInorder;
int* leftPreorderEnd = startPreorder+leftLength;//在中序找到左子树
if(leftLength>0){
root->left = constructCore(startPreorder+1,leftPreorderEnd,
startInorder,rootInorder-1);
}
int rightLength = endInoder-rootInorder;
if(rightLength>0){
root->right = constructCore(leftPreorderEnd+1,endPreorder,rootInorder+1,endInoder);
}
return root;
}
BinaryTreeNode* contruct(int *preOder,int* inOrder,int length){
if(preOder==NULL||inOrder==NULL||length<=0){
return NULL;
}
return constructCore(preOder,preOder+length-1,inOrder,inOrder+length-1);
}

void postOrderPrint(BinaryTreeNode* root){
if(root==NULL){
return;
}
postOrderPrint(root->left);
postOrderPrint(root->right);
printf("%d ",root->value);
}
int main(){
int n;
while(scanf("%d",&n)!=EOF){
int *a = new int
;
int *b = new int
;
for(int i=0;i<n;i++){
scanf("%d",&a[i]);
}
for(int i=0;i<n;i++){
scanf("%d",&b[i]);
}
try{
BinaryTreeNode *  root  = contruct(a,b,n);
postOrderPrint(root);
printf("\n");
}catch(const char * str){
printf("%s\n","No");
}

}

return 0;
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: