输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
#include<iostream>
#include<vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) {
val = x;
left = NULL;
right = NULL;
}
};
class Solution {
public:
TreeNode* reConstructBinaryTree(vector<int> pre, vector<int> vin) {
if (pre.empty() || vin.empty())
return NULL;
//在前序遍历中prev中找根节点,并确定其在vin的位置
size_t index = 0;
for (; index<vin.size(); index++)
{
if (vin[index] == pre[0])
break;
}
//已经找到根节点,并构造根节点
TreeNode* root = new TreeNode(pre[0]);
//Print(root);
//根据中序遍历将根节点左右两侧一分为二,根节点的左侧为左子树,右侧为右子树
vector<int> prev_left, prev_right;
vector<int> vin_left, vin_right;
//先将前序、中序中根节点的左右子树记录下来
for (size_t j = 0; j<index; j++)
{
prev_left.push_back(pre[j + 1]);
vin_left.push_back(vin[j]);
}
for (size_t j = index + 1; j<vin.size(); j++)
{
prev_right.push_back(pre[j]);
vin_right.push_back(vin[j]);
}
//递归构造左右子树
root->left = reConstructBinaryTree(prev_left, vin_left);
root->right = reConstructBinaryTree(prev_right, vin_right);
return root;
}
void printTree(TreeNode *root) {
if (root) {
cout << root->val << " ";
printTree(root->left);
printTree(root->right);
}
}
};
int main()
{
vector<int> pre= { 1, 2, 4, 7, 3, 5, 6, 8 };
vector<int> vin = { 4,7,2,1,5,3,8,6 };
Solution so;
TreeNode *root= so.reConstructBinaryTree(pre, vin);
so.printTree(root);
return 0;
}