https://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6
思路:先找出根结点,再递归构建左右子树
class Solution {
public:
TreeNode *reConstructBinaryTree(vector<int> pre, vector<int> vin) {
if (pre.empty() && vin.empty()) // 树为空
return nullptr;
TreeNode *root = new TreeNode(*pre.begin()); // 前序遍历的第一个结点为根结点
// 在中序遍历中找到根结点的位置
auto mid = find(vin.begin(),vin.end(),root->val);
vector<int> leftin{vin.begin(),mid}; // 左子树的中序遍历序列
vector<int> rightin{mid+1,vin.end()}; // 右子树的中序遍历序列
int nleft = leftin.size(); // 左子树中的结点个数
int nright = rightin.size(); // 右子树中的结点个数
vector<int> leftpre{pre.begin()+1,pre.begin()+nleft+1}; // 左子树的前序遍历序列
vector<int> rightpre{pre.end()-nright,pre.end()}; // 右子树的前序遍历序列
if (nleft) // 左子树不为空
root->left = reConstructBinaryTree(leftpre,leftin); // 递归构建左子树
if (nright) // 右子树不为空
root->right = reConstructBinaryTree(rightpre,rightin); // 递归构建右子树
return root; // 返回树根
}
};