根据二叉树的前序和中序遍历序列构建二叉树。若有多个可能解,则输出一个。
struct NODE{
NODE* pLeft;
NODE* pRight;
char chValue;
};
bool Rebuild(char* pPreOrder,char* pInOrder,int nTreeLen,NODE** pRoot)
{
if(nTreeLen==0)
{
*pRoot=NULL;
return true;
}
*pRoot=new NODE();
(*pRoot)->chValue=pPreOrder[0];
int parentIndexIn=0;
for(int i=0;i<nTreeLen;i++)
{
if (pPreOrder[0]==pInOrder[i])
{
parentIndexIn=i;
if(Rebuild(&pPreOrder[1],pInOrder,parentIndexIn,&((*pRoot)->pLeft))
&&Rebuild(&pPreOrder[parentIndexIn+1],&pInOrder[parentIndexIn+1],nTreeLen-parentIndexIn-1,&((*pRoot)->pRight)))
return true;
}
}
return false;
}
int main()
{
char* preOrder="abdccf";
char* inOrder="dbaccf";
NODE** pRoot=new NODE*;
Rebuild(preOrder,inOrder,6,pRoot);
return 0;
}
本文详细介绍了如何根据给定的二叉树前序和中序遍历序列构建二叉树的过程,包括算法实现及示例代码。

被折叠的 条评论
为什么被折叠?



