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

来源:互联网 发布:淘宝上卖什么最赚钱 编辑:程序博客网 时间:2024/05/29 16:19
// BinaryTree.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include <iostream>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;//如果左边长度大于0if (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<<root->m_nValue<<endl;}if (root->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;}

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