从先序遍历和中序遍历结果重建二叉树

问题:给定二叉树的先序遍历和中序遍历字符串结果,重建二叉树。

思路:假设先序遍历和后续遍历结果为A和B,利用A[0]在B中的位置pCut可以将A和B分别划分成三个部分,B中pCut左侧将构成二叉树的左子树,pCut右侧的将构成右子树。

代码:

#include <iostream>
#include <iomanip>
using namespace std;

typedef struct BTNode 
{
	char data;
	BTNode * lChild,*rChild;
} BTNode,*BTree;

void Rebuild(char *pPreSeq,char *pInSeq,int TreeLen, BTree *pRoot)
{
	if(pPreSeq == NULL || pInSeq == NULL)
		return;
	/* Create New Node*/
	BTNode * pNode = new BTNode;
	pNode->data = *pPreSeq;
	pNode->lChild = pNode->rChild = NULL;
	
	if(*pRoot == NULL)
		*pRoot = pNode;
	if(TreeLen == 1)
		return;
	/* left and right Bin Tree cut*/
	char *pCut = pInSeq;
	int tmpLen = 0;
	while(*pCut != *pPreSeq)
	{
		if(pCut == NULL || pPreSeq == NULL)
			return;
		tmpLen++;
		if(tmpLen > TreeLen)
			break;
		pCut++;
	} 
	int nLeftLen = 0;
	nLeftLen = (int)(pCut - pInSeq);
	int nRightLen = 0;
	nRightLen = TreeLen - nLeftLen - 1;
	/* recursively rebuild the left and right child */
	if(nLeftLen)
		Rebuild(pPreSeq+1,pInSeq,nLeftLen,&((*pRoot)->lChild));
	if(nRightLen)
		Rebuild(pPreSeq+nLeftLen+1,pInSeq+nLeftLen+1,nRightLen,&((*pRoot)->rChild)); 
}

void PostOrderTraverse(BTree T)
{
	if(T){
		PostOrderTraverse(T->lChild);
		PostOrderTraverse(T->rChild);
		cout<<setw(3)<<left<<T->data; 
	} 
}

void ClearBTree(BTree *T)
{
	if(*T)
	{
		ClearBTree(&((*T)->lChild));
		ClearBTree(&((*T)->rChild));
		delete (*T);
		*T = NULL;
	}
}
int main()
{
	char cPre[6] = {'a','b','d','c','e','f'};
	char cIn[6] = {'d','b','a','e','c','f'};
	BTree T = NULL;
	Rebuild(cPre,cIn,6,&T);
	PostOrderTraverse(T);
	ClearBTree(&T);
}
输出:

d  b  e  f  c  a  

REF:

1,编程之美 3.9


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值