题目:已知二叉树的前序遍历和中序遍历结果,重建二叉树。假设不出现重复值的树节点。
#include <iostream>
using namespace std;
typedef struct BSTree
{
int val;
BSTree*leftchild;
BSTree*rightchild;
}*BSTreePoint;
BSTree *constructCore(int *preStart,int *preEnd,int *inorderStart,int *inorderEnd);
BSTree *construct(int *preorder,int *inorder,int len)
{
if (preorder==NULL||inorder==NULL||len<1)
{
cout<<"构造条件错误\n";
}
return constructCore(preorder,preorder+len-1,inorder,inorder+len-1);
}
BSTree *constructCore(int *preStart,int *preEnd,int *inorderStart,int *inorderEnd)
{
int rootValue=preStart[0];
BSTree *root=new BSTree;
root->val=rootValue;
root->leftchild=root->rightchild=NULL;
if (preStart==preEnd)
{
if ((inorderStart==inorderEnd)&&(*preStart==*inorderStart))
//递归到子树只有一个节点情况,如果前序和中序值不相等为非法输入
{
return root;//递归结束条件
}
else
{
cout<<"Invalid input order \n";
}
}
int *rootInorder=inorderStart;
while (rootInorder<=inorderEnd&&*rootInorder!=rootValue)
{
rootInorder++;
}
if (rootInorder>inorderEnd)
{
cout<<"Invalid input \n";
}
int leftlen=rootInorder-inorderStart;
int *preleftEnd=preStart+leftlen;
if (leftlen>0)
{
//递归建左子树
root->leftchild=constructCore(preStart+1,preleftEnd,inorderStart,rootInorder-1);
}
if (leftlen<(preEnd-preStart))//如果右子树有节点
{
root->rightchild=constructCore(preStart+leftlen+1,preEnd,rootInorder+1,inorderEnd);
}
return root;
}
void PreOrder(BSTree *root)
{
if (root!=NULL)
{
cout<<root->val<<" ";
PreOrder(root->leftchild);
PreOrder(root->rightchild);
}
}
void InOrder(BSTree *root)
{
if (root!=NULL)
{
InOrder(root->leftchild);
cout<<root->val<<" ";
InOrder(root->rightchild);
}
}
int main()
{
int pre[]={1,2,4,7,3,5,6,8};
int inorder[]={4,7,2,1,5,3,8,6};
BSTree *root=construct(pre,inorder,8);
PreOrder(root);
cout<<endl;
InOrder(root);
cout<<endl;
}
思想来源于:剑指offer ,感谢作者。