✅做题思路or感想:
- 根据前序遍历找根节点
- 由前序遍历根节点的值来切割中序数组,再由中序数组切割前序数组,最终切割成左子树的中序,前序数组和右子树的中序,前序数组。
- 递归造根节点的左子树和右子树
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
if (preorder.size() == 0 || inorder.size() == 0)return nullptr; //如果数组空,则是空节点
int val = preorder[0]; //找前序数组的第一个,便是根节点的值
TreeNode* root = new TreeNode(val);
if (preorder.size() == 1)return root; //找到的是最后一个根节点,则返回
int index;
//切割中序数组
for (int i = 0; i < inorder.size(); i++) {
if (inorder[i] == val) {
index = i;
break;
}
}
//造左子树,右子树的前,中序数组
vector<int>leftPre (preorder.begin() + 1, preorder.begin()+ 1 + index);
vector<int>leftIn (inorder.begin(), inorder.begin() + index);
vector<int>rightPre (preorder.begin() + index + 1, preorder.end());
vector<int>rightIn (inorder.begin() + index + 1, inorder.end());
//造出左子树,右子树
root->left = buildTree(leftPre, leftIn);
root->right = buildTree(rightPre, rightIn);
return root;
}
};