需要注意两点:1、对于前序遍历第一个即为根节点。2、在前序遍历找到根节点之后,在中序遍历中根节点之前的全部为根节点的左子树,后面的全部为右子树。所以可以根据中序遍历中根节点之前的数量,在前序遍历中找出左子树。3、递归实现就可以。
TreeNode* reConstructBinaryTree(vector<int> pre, vector<int> vin)
{
int len = pre.size();
if (len == 0)return NULL;
vector<int>pre_left, pre_right, in_left, in_right;
int temp = pre[0];
int root = 0;
TreeNode* head = (TreeNode*)malloc(sizeof(TreeNode));
head->val = pre[0];
for (int i = 0; i < len; i++)
{
if (temp == vin[i])
{
root = i;
break;
}
}
for (int j = 0; j < root; j++)
{
pre_left.push_back(pre[j + 1]);
in_left.push_back(vin[j]);
}
for (int j = root + 1; j < len; j++)
{
pre_right.push_back(pre[j]);
in_right.push_back(vin[j]);
}
head->left = reConstructBinaryTree(pre_left, in_left);
head->right = reConstructBinaryTree(pre_right, in_right);
return head;
}