给定一棵二叉树的先序遍历序列和中序遍历序列,重建这棵二叉树。
//当前先序序列区间为【preL,preR】
//当前中序序列区间为【inL,inR】
//返回根结点地址
Node* create(int preL,int preR,int inL,int inR)
{if(preL>preR) return NULL;Node* root=new Node;root->data=pre[preL];int k;for(k=inL;k<=inR;k++){if(in[k]==pre[preL]) break;}int numLeft=k-inL;root->lchild=create(preL+1,preL+numLeft,inL,k-1);root->rchild=create(preL+numLeft+1,preR,k+1,inR); return root;
}
在中序序列中找到 in【k】==pre【L】的结点。
int k;for(k=inL;k<=inR;k++){if(in[k]==pre[preL]) break;}