#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:
struct TreeNode* reConstructBinaryTree(vector<int> pre, vector<int> in){
vector<int> left_pre, left_in, right_pre, right_in;
int pos = 0;
if (in.size() == 0)
return NULL;
TreeNode* node = new TreeNode(pre[0]);//重建二叉树,根结点为前序二叉树的第一个元素
//在中序二叉树中查找根节点,以便分割左右子树
for (int i = 0; i < in.size(); ++i) {
if (pre[0] == in[i]) {
pos = i;
break;
}
}
//左子树前序和中序序列
for (int i = 1; i < pos + 1; ++i) {
left_pre.push_back(pre[i]);
left_in.push_back(in[i-1]);
}
//右子树前序和中序序列
for (int i = pos + 1; i < in.size(); ++i) {
right_pre.push_back(pre[i]);
right_in.push_back(in[i]);
}
//递归查找左右子树根节点
node->left = reConstructBinaryTree(left_pre, left_in);
node->right = reConstructBinaryTree(right_pre, right_in);
//返回节点
return node;
}
//vector<int> preTrav, inTrav;
//前序遍历
void preOrder(struct TreeNode* &root) {
if (root == NULL)
return;
cout << root->val;
//preTrav.push_back(root->val);
preOrder(root->left);
preOrder(root->right);
}
};
int main()
{
Solution s;
vector<int> pre = { 1, 2, 4, 7, 3, 5, 6, 8 };
vector<int> in = { 4, 7, 2, 1, 5, 3, 8, 6 };
TreeNode* root= s.reConstructBinaryTree(pre, in);
s.preOrder(root);
cout<<endl;
return 0;
}
Reference: https://www.cnblogs.com/letgo/p/5715758.html