已知前序和中序遍历恢复二叉树(递归)

来源:互联网 发布:python视频教程 编辑:程序博客网 时间:2024/05/07 07:32

 

#include<iostream>using namespace std;#define TREELEN  6//数据结构定义struct NODE{NODE* pLeft;         //左子树NODE* pRight;        //右子树char chValue;        //该节点的值};void ReBuild(char* pPreOrder,char* pInOrder,int nTreeLen,NODE** pRoot){//检查边界条件if(pPreOrder==NULL || pInOrder==NULL){return;}//获得前序遍历的第一个节点NODE* pTemp = new NODE;pTemp->chValue = *pPreOrder;pTemp->pLeft   = NULL;pTemp->pRight  = NULL;//如果节点为空,把当前节点复制到根节点if(*pRoot == NULL){*pRoot = pTemp;}//如果当前树长度为1,那么已经是最后一个节点if(nTreeLen == 1){return;}//寻找子树长度char* pOrgInOrder = pInOrder;char* pLeftEnd = pInOrder;    int nTempLen = 0;//找到左子树的结尾while(*pPreOrder != *pLeftEnd){if(pPreOrder==NULL || pLeftEnd==NULL){return;}nTempLen++;//记录临时长度,以免溢出if(nTempLen > nTreeLen){break;}pLeftEnd++;}//寻找左子树长度int nLeftLen = 0;nLeftLen = (int)(pLeftEnd-pOrgInOrder);//寻找右子树长度int nRightLen = 0;nRightLen = nTreeLen - nLeftLen - 1;//重建左子树if(nLeftLen > 0){ReBuild(pPreOrder+1,pInOrder,nLeftLen,&((*pRoot)->pLeft));}//重建右子树if(nRightLen > 0){ReBuild(pPreOrder+nLeftLen+1,pInOrder+nLeftLen+1,nRightLen,&((*pRoot)->pRight));}}//前序遍历结果void PrePrint(NODE* pRoot){if(pRoot == NULL){return;}cout<<pRoot->chValue<<" ";PrePrint(pRoot->pLeft);PrePrint(pRoot->pRight);}//中序遍历结果void InPrint(NODE* pRoot){if(pRoot == NULL){return;}InPrint(pRoot->pLeft);cout<<pRoot->chValue<<" ";InPrint(pRoot->pRight);}void main(){char szPreOrder[TREELEN] = {'a','b','d','c','e','f'};char szInOrder[TREELEN]  = {'d','b','a','e','c','f'};NODE* pRoot = NULL;ReBuild(szPreOrder,szInOrder,TREELEN,&pRoot);PrePrint(pRoot);cout<<endl<<endl;;InPrint(pRoot);cout<<endl;}/*a b d c e fd b a e c f*/


 

原创粉丝点击