重建二叉树

对于一颗二叉树,可以根据先序遍历(后序遍历)和中序遍历重新还原出二叉树。比如前序遍历为{1,2,4,7,3,5,6,8},中序遍历为{4, 7, 2, 1,5,3,8,6}。

根据先序遍历和中序遍历还原二叉树的主要思想:

1、先序遍历序列的第一个元素必定是根节点,可以由此获取二叉树的根节点。

2、根据根节点,在中序遍历序列中查找该节点,由中序遍历的性质可知,中序遍历中该根节点左边的序列必定在根节点的左子树中,而根节点右边的序列必定在右子树中。由此可以知道先序遍历中左子树以及右子树的起止位置。

3、分别对左子树和右子树重复上述的过程,直至所有的子树的起止位置相等时,说明已经到达叶子节点,遍历完毕。


代码如下:

#include <iostream>
using namespace std;

typedef struct node{
	int data;
	node* left;
	node* right;
}*nodePtr;

void ReBuild(int *preStart, int *preEnd, int *inStart, int *inEnd, nodePtr &rootPtr)
{
	if (preStart > preEnd || inStart > inEnd || !preStart || !inStart)
		return;
	else
	{
		int rootVal = *preStart;
		int *rootIndex = find(inStart, inEnd, rootVal);
		rootPtr = new node;
		rootPtr->data = rootVal;
		rootPtr->left = NULL;
		rootPtr->right = NULL;
		if (rootIndex != inEnd + 1)
		{
			int leftLen = rootIndex - inStart;
			ReBuild(preStart + 1, preStart + leftLen, inStart, rootIndex - 1, rootPtr->left);
			ReBuild(preStart + leftLen + 1, preEnd, rootIndex + 1, inEnd,  rootPtr->right);
		}
	}
}

void InTraverse(nodePtr &a)
{
	if (a != NULL)
	{
		InTraverse(a->left);
		cout << a->data << endl;
		InTraverse(a->right);
	}
}


int main()
{
	int pre[] = { 1, 2, 4, 7, 3, 5, 6, 8};
	int in[] = { 4, 7, 2, 1, 5, 3, 8, 6 };
	nodePtr rootPtr = NULL;
	ReBuild(pre, pre + 7, in, in + 7, rootPtr);
	InTraverse(rootPtr);
	system("pause");
	return 0;
}

发布了38 篇原创文章 · 获赞 4 · 访问量 3万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章