基本步骤是这样:
- 先看先序序列,可以确定根节点,然后在中序遍历中就可以将二叉树划成左子树和右子树两拨
- 对左右子树递归上述步骤
好像直到怎么遍历二叉树,却对怎么重建二叉树没什么经验
从上往下建还是从下往上建呢?又怎么和两个序列的访问结合起来呢?
递归写法
递归需要更新标明每次构建时,前序和中序的序列左右边界
class Solution {
private:
unordered_map<int, int> index;
public:
TreeNode* myBuildTree(const vector<int>& preorder, const vector<int>& inorder, int preorder_left, int preorder_right, int inorder_left, int inorder_right) {
if (preorder_left > preorder_right) return nullptr;
int preorder_root = preorder_left;// 前序根节点索引
int inorder_root = index[preorder[preorder_root]];// 中序根节点索引
TreeNode* root = new TreeNode(preorder[preorder_root]);
int size_of_leftsub = inorder_root - inorder_left;
root->left = myBuildTree(preorder, inorder, preorder_left + 1, preorder_left +size_of_leftsub, inorder_left, inorder_root - 1);
root->right = myBuildTree(preorder, inorder, preorder_left + size_of_leftsub + 1, preorder_right, inorder_root + 1, inorder_right);
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int n = preorder.size();
// 倒转索引和值的哈希映射,方便快速定位
for (int i = 0; i < n; i++) index[inorder[i]] = i;
return myBuildTree(preorder, inorder, 0, n - 1, 0, n - 1);
}
};