知道前序遍历和中序遍历编写程序得到二叉树

// BinaryTree.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include 
using namespace std;

struct  BTreeNode
{
	int        m_nValue;
	BTreeNode* m_pLeft;
	BTreeNode* m_pRight;
};

BTreeNode* ConstructCore(int* startPreorder, int* endPreorder, int* startInorder, int* endInorder)
{
	//前序遍历序列的第一个数字是根节点的值
	int rootValue = startPreorder[0];
	BTreeNode* root = new BTreeNode();
	root->m_nValue = rootValue;
	root->m_pLeft  =  NULL;
	root->m_pRight =  NULL;


	if (startPreorder == endPreorder)
	{
		if (startInorder == endInorder && *startPreorder == *startInorder)
		{
			return root;
		}
		else
		{
			throw std::exception("Invalid input");
		}

	}



	//在中序遍历中找到根节点的值
	int* rootInorder = startInorder;
	while (rootInorder <= endInorder && *rootInorder != rootValue)
	{
		++rootInorder;
	}
	//判断是否存在要找的根节点
	if (rootInorder == endInorder && *rootInorder != rootValue)
	{
		throw std::exception("Invalid input");
	}


	int leftLength  = rootInorder - startInorder;
	int* leftPreorderEnd = startPreorder + leftLength;
	//如果左边长度大于0
	if (leftLength > 0)
	{
		//构建左子树
		root->m_pLeft = ConstructCore(startPreorder+1,leftPreorderEnd,startInorder,rootInorder-1);
	}
	if (leftLength < endPreorder - startPreorder)
	{
		//构建右子树
		root->m_pRight = ConstructCore(leftPreorderEnd+1,endPreorder,rootInorder+1,endInorder);
	}
	return root;
}

BTreeNode* Construct(int* preOrder, int* inOrder, int length)
{
	if (preOrder == NULL || inOrder == NULL || length <= 0)
	{
		return NULL;
	}
	else
	{
		return ConstructCore(preOrder,preOrder+ length -1, inOrder,inOrder + length -1);
	}
}

void PrintTree(BTreeNode* root)
{
	
	if (root->m_pLeft != NULL)
	{
		PrintTree(root->m_pLeft);
	}
	if (root != NULL)
	{
		cout<m_nValue<m_pRight != NULL)
	{
		PrintTree(root->m_pRight);
	}
}

int _tmain(int argc, _TCHAR* argv[])
{

	int p[] ={1,2,4,7,3,5,6,8};
	int q[] ={4,7,2,1,5,3,8,6};
	BTreeNode* tree = Construct(p,q,8);
	PrintTree(tree);


	getchar();
	return 0;
}

前序遍历的第一个数字就是根节点的值!知道前序遍历和中序遍历可以得到二叉树的结果!

你可能感兴趣的:(c/c++)