Construct Binary Tree From Inorder And Postorder Traversal Problem


Description

LeetCode Problem 106.

Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree.

Example 1:

1
2
Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
Output: [3,9,20,null,null,15,7]

Example 2:

1
2
Input: inorder = [-1], postorder = [-1]
Output: [-1]

Constraints:

  • 1 <= inorder.length <= 3000
  • postorder.length == inorder.length
  • -3000 <= inorder[i], postorder[i] <= 3000
  • inorder and postorder consist of unique values.
  • Each value of postorder also appears in inorder.
  • inorder is guaranteed to be the inorder traversal of the tree.
  • postorder is guaranteed to be the postorder traversal of the tree.


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
    return create(inorder, postorder, 0, inorder.size() - 1, 0, postorder.size() - 1);
}

TreeNode* create(vector<int> &inorder, vector<int> &postorder, int is, int ie, int ps, int pe){
    if(ps > pe){
        return nullptr;
    }
    TreeNode* node = new TreeNode(postorder[pe]);
    int pos;
    for(int i = is; i <= ie; i++){
        if(inorder[i] == node->val){
            pos = i;
            break;
        }
    }
    node->left = create(inorder, postorder, is, pos - 1, ps, ps + pos - is - 1);
    node->right = create(inorder, postorder, pos + 1, ie, pe - ie + pos, pe - 1);
    return node;
}




Related Posts

Vertical Order Traversal Of A Binary Tree Problem

LeetCode 987. Given the root of a binary tree, calculate...

Univalued Binary Tree Problem

LeetCode 965. A binary tree is uni-valued if every node...

Sum Of Distances In Tree Problem

LeetCode 834. There is an undirected connected tree with n...

Smallest Subtree With All The Deepest Nodes Problem

LeetCode 865. Given the root of a binary tree, the...

Smallest String Starting From Leaf Problem

LeetCode 988. You are given the root of a binary...

Similar String Groups Problem

LeetCode 839. Two strings Xand Yare similar if we can...