#106

Construct Binary Tree from Inorder and Postorder Traversal

Medium
ArrayHash TableDivide and ConquerTreeBinary TreeHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses a hashmap to store the indices of elements in the inorder array, allowing for O(1) access time. This reduces the overall time complexity significantly.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a hashmap to store the indices of elements in the inorder array.
  2. 2Step 2: Define a recursive function that takes the current bounds of the inorder and postorder arrays.
  3. 3Step 3: Identify the root from the postorder array and use the hashmap to find its index in the inorder array in O(1).
  4. 4Step 4: Recursively construct the right and left subtrees using the updated bounds.
solution.py19 lines
1class TreeNode:
2    def __init__(self, val=0, left=None, right=None):
3        self.val = val
4        self.left = left
5        self.right = right
6
7class Solution:
8    def buildTree(self, inorder, postorder):
9        index_map = {val: idx for idx, val in enumerate(inorder)}
10        def build(in_left, in_right):
11            if in_left > in_right:
12                return None
13            root_val = postorder.pop()
14            root = TreeNode(root_val)
15            index = index_map[root_val]
16            root.right = build(index + 1, in_right)
17            root.left = build(in_left, index - 1)
18            return root
19        return build(0, len(inorder) - 1)

Complexity note: The time complexity is O(n) because we traverse the inorder and postorder arrays once to build the tree and create the hashmap. The space complexity is O(n) due to the hashmap storing indices.

  • 1Understanding tree traversal methods is crucial.
  • 2Using a hashmap can significantly reduce lookup times.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.