Quantcast
Channel: CSDN博客推荐文章
Viewing all articles
Browse latest Browse all 35570

已知前序和中序遍历恢复二叉树

$
0
0

 

#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 f

d b a e c f
*/


 

作者:themagickeyjianan 发表于2013-7-17 13:32:15 原文链接
阅读:35 评论:0 查看评论

Viewing all articles
Browse latest Browse all 35570

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>