您的位置:首页 > 编程语言

编程之美3.9 重建二叉树

2013-09-10 22:00 393 查看
根据二叉树的前序和中序遍历序列构建二叉树。若有多个可能解,则输出一个。

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: