105. Construct Binary Tree from Preorder and Inorder Traversal

Given preorder and inorder traversal of a tree, construct the binary tree.

Note: You may assume that duplicates do not exist in the tree.

For example, given

preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]

Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7

需要有一個關係是能從數值快速得到inorder裡數字所在的index,所以使用一個unordered_map去紀錄數字對應到的位置。這樣Recursion的時候就可以有效率地得到inorder數列的切分點。

TreeNode* build(vector<int>& preorder, int pLeft, int pRight, vector<int>& inorder, int iLeft, int iRight, 
                unordered_map<int, int>& m) {
    if (pLeft > pRight || iLeft > iRight) return nullptr;
    int i = m[preorder[pLeft]]; // the root index in inorder traversal
    TreeNode* cur = new TreeNode(preorder[pLeft]);
    cur->left = build(preorder, pLeft + 1, pLeft + i - iLeft, inorder, iLeft, i - 1, m);
    cur->right = build(preorder, pLeft + i - iLeft + 1, pRight, inorder, i + 1, iRight, m);
    return cur;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { // time: O(n); space: O(n)
    // record the corresponding index of numbers in inorder traversal
    unordered_map<int, int> m;
    for (int i = 0; i < inorder.size(); ++i) {
        m[inorder[i]] = i;
    }
    return build(preorder, 0, preorder.size() - 1, inorder, 0, inorder.size() - 1, m);
}
106. Construct Binary Tree from Inorder and Postorder Traversal

Last updated

Was this helpful?