题目描述:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
//Definition for binary tree
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
//重建二叉树--版本1
struct TreeNode* reConstructBinaryTree(vector<int> pre, vector<int> in)
{
if (pre.size() == 0)
return NULL;
TreeNode* root = new TreeNode(pre[0]);
vector<int> LeftPre, RightPre, LeftIn, RightIn;
bool flag = false;
for (int i = 0;i < pre.size();++i)
{
if (in[i] == pre[0])
{
flag = true;
continue;
}
if (flag == false)
{
LeftPre.push_back(pre[i+1]);
LeftIn.push_back(in[i]);
}
else
{
RightPre.push_back(pre[i]);
RightIn.push_back(in[i]);
}
}
root->left = reConstructBinaryTree(LeftPre, LeftIn);
root->right = reConstructBinaryTree(RightPre, RightIn);
return root;
}
//重建二叉树--版本2
struct TreeNode* ConstructBTree(vector<int>::iterator PreBegin, \
vector<int>::iterator PreEnd, \
vector<int>::iterator InBegin, \
vector<int>::iterator InEnd)
{
int rootval = PreBegin[0];
TreeNode* root = new TreeNode(rootval);
if (PreBegin == PreEnd)
{
if (InBegin == InEnd && *PreBegin == *InBegin)
{
return root;
}
else
{
return NULL;
}
}
//在中序遍历中寻找根节点的值
vector<int>::iterator PointIn = InBegin;
while (PointIn != InEnd && *PointIn != rootval)
++PointIn;
if (PointIn == InEnd&&*PointIn != rootval)
return NULL;
int gap = PointIn - InBegin;
vector<int>::iterator LeftPreEnd = PreBegin + gap;
if (gap > 0)
{
root->left = ConstructBTree(PreBegin,LeftPreEnd,InBegin,PointIn-1);
}
if (gap < PreBegin - PreEnd)
{
root->right= ConstructBTree(LeftPreEnd+1,PreEnd, PointIn+1,InEnd);
}
return root;
}
struct TreeNode* reConstructBinaryTree(vector<int> pre, vector<int> in)
{
if (pre.size() == 0 || in.size() == 0)
return NULL;
return ConstructBTree(pre.begin(), pre.end() - 1, in.begin(), in.end() - 1);
}