#include <iostream>
using namespace std;
typedef struct Binary_Node
{
int value;
struct Binary_Node *left;
struct Binary_Node *right;
}BinaryNode;
int pre_order[1010];
int in_order[1010];
int flag;
BinaryNode *BuildTree(int *start_pre,int *end_pre,
int *start_in,int *end_in)
{
BinaryNode *root=new BinaryNode;
root->value=*start_pre;
root->left=root->right=NULL;
if(start_pre== end_pre)
{
if(start_in==end_in && *start_pre==*start_in)
return root;
else
{
flag=0;
}
}
//在中跟序列中找到根节点的值
int *rootInOrder=start_in;
while(rootInOrder<=end_in&& *rootInOrder!=root->value)
rootInOrder++;
int leftLength = rootInOrder-start_in;
int rightLength = end_in - rootInOrder;
int *leftPriEnd = start_pre+leftLength;
if (leftLength >0)
{
root->left= BuildTree(start_pre+1,leftPriEnd,start_in,rootInOrder-1);
}
else
{
//flag=0;
}
if(leftLength<end_pre- start_pre)
{
root->right=BuildTree(leftPriEnd+1,end_pre,rootInOrder+1,end_in);
}
else
{
//flag=0;
}
return root;
}
void print(BinaryNode *root)
{
if(root!=NULL)
{
print(root->left);
print(root->right);
if(root!=NULL)
{
cout<<root->value<<' ';
}
}
}
int main()
{
int length;
while(cin>>length)
{
for(int i=0;i<length;i++)
cin>>*(pre_order+i);
for(int i=0;i<length;i++)
cin>>*(i+in_order);
flag=1;
BinaryNode *node=new BinaryNode;
int *start_pre=&pre_order[0];
int *end_pre =&pre_order[length-1];
int *start_in =&in_order[0];
int *end_in =&in_order[length-1];
node=BuildTree(start_pre,end_pre,start_in,end_in);
if (flag)
{
print(node);
cout<<endl;
}
else cout<<"No"<<endl;
}
return 0;
}
《剑指offer》面试题6 重建二叉树
最新推荐文章于 2014-12-14 16:37:42 发布