描述
Given preorder and inorder traversal of a tree, construct the binary tree.
Note: You may assume that duplicates do not exist in the tree.
Given preorder and inorder traversal of a tree, construct the binary tree.
Note: You may assume that duplicates do not exist in the tree.
#include "BinaryTree.h"
#include<vector>
using namespace std;
//===由前序和中序构建二叉树
BinaryTreeNode* ConBinTreeFromPreAndMid(int pre[],int prebegin, int mid[], int midbegin,int length)
{
if (length <= 0) return NULL;
BinaryTreeNode* proot = CreateBinaryTreeNode(pre[prebegin]);
ConnectTreeNodes(proot, NULL,NULL);
int index = midbegin;
for (int i = midbegin; i < midbegin+length; i++)
{
if (pre[prebegin] == mid[i])
{
index = i; break;
}
}
int prelength = index - midbegin;
int lastlength = length - prelength-1;
proot->m_pLeft=ConBinTreeFromPreAndMid(pre, prebegin+1, mid, midbegin,prelength);
proot->m_pRight = ConBinTreeFromPreAndMid(pre, prebegin+prelength+1,mid ,index + 1,lastlength);
return proot;
}
// ====================测试代码====================
int main()
{
const int n = 9;
int pre[n] = { 1, 5, 7, 8, 11, 9, 3, 4,10};
int mid[n] = { 7, 5, 8, 1, 3, 9, 4, 11,10};
BinaryTreeNode *proot = ConBinTreeFromPreAndMid(pre,0, mid,0,n);
PrintTree(proot);
DestroyTree(proot);
}