問題:根據二叉樹的先序和中序建構二叉樹
思路:每次根據先序和中序順序确定根節點和相應的左右子樹,再分别對左右子樹進行遞歸确定
程式實作:
#include <iostream>
using namespace std;
typedef struct Btree
{
int num;
struct Btree *lchild;
struct Btree *rchild;
}Btree,*PBtree;
PBtree construct_tree(int *start_pre,int *end_pre, int *start_in, int *end_in)
{
PBtree root;
root=new Btree();
int rootvalue=start_pre[0];
root->num=rootvalue;
root->lchild=NULL;
root->rchild=NULL;
if(start_pre==end_pre)
{
if(start_in==end_in &&(*start_pre)==(*start_in))
return root;
else
{
cout<<root->num<<endl;
cout<<"wrong1 input"<<endl;
return NULL;
}
}
int *rootInorder=start_in;
while(rootInorder<=end_in&&(*rootInorder)!=rootvalue)
rootInorder++;
if(rootInorder==end_in&&(*rootInorder)!=rootvalue)
{
cout<<"wrong2 input"<<endl;
return NULL;
}
int leftLength=rootInorder-start_in;
int *leftPreEnd=start_pre+leftLength;
if(leftLength>0)
{
//root->lchild=construct_tree(start_pre+1,start_pre+leftLength,start_in,rootInorder-1);
root->lchild=construct_tree(start_pre+1,leftPreEnd,start_in,rootInorder-1);
}
if(leftLength<end_pre-start_pre)
{
root->rchild=construct_tree(leftPreEnd+1,end_pre,rootInorder+1,end_in);
}
return root;
}
PBtree construct_init(int *preorder,int *inorder,int length)
{
if(preorder==NULL||inorder==NULL||length<0)
return NULL;
return construct_tree(preorder,preorder+length-1,inorder,inorder+length-1);
}
void presearch(PBtree root)
{
if(root==NULL)
return ;
cout<<root->num<<" ";
presearch(root->lchild);
presearch(root->rchild);
}
void insearch(PBtree root)
{
if(root==NULL)
return ;
insearch(root->lchild);
cout<<root->num<<" ";
insearch(root->rchild);
}
void postsearch(PBtree root)
{
if(root==NULL)
return ;
postsearch(root->lchild);
postsearch(root->rchild);
cout<<root->num<<" ";
}
int main()
{
int a[11]={5,6,1,4,2,3,4,7,8,9,10};
int b[11]={4,1,6,2,3,5,7,4,8,9,10};
PBtree root=construct_init(a,b,11);
presearch(root);
cout<<endl;
insearch(root);
cout<<endl;
postsearch(root);
cout<<endl;
return 0;
}
輸出結果:
5 6 1 4 2 3 4 7 8 9 10
4 1 6 2 3 5 7 4 8 9 10
4 1 3 2 6 7 10 9 8 4 5