106. Construct Binary Tree from Inorder and Postorder Traversal ๐
Last updated
Last updated
Difficulty: Medium
- Tags: Binary Tree
, Divide and Conquer
, Recursion
Given two integer arrays inorder
and postorder
:
inorder
represents the inorder traversal of a binary tree.
postorder
represents the postorder traversal of the same binary tree.
Construct and return the binary tree.
๐น Example 1:
Input:
Output:
๐น Example 2:
Input:
Output:
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.
To construct the binary tree:
The last value in postorder
is the root node.
Find the root node's position in inorder
. Values to the left belong to the left subtree, and values to the right belong to the right subtree.
Recursively repeat this process for the left and right subtrees.
Postorder Traversal:
The last element is the root.
The second-to-last element is part of the right subtree.
Inorder Traversal:
Left subtree elements come before the root.
Right subtree elements come after the root.
Recursive Construction:
Use the postorder
array to pick the root.
Divide the inorder
array into left and right subtrees.
Recursively construct the tree for both subtrees.
O(n), where n
is the number of nodes. Each node is visited once, and the HashMap
provides O(1)
lookups for the index.
O(n) for the HashMap
and recursive stack space.
Could you modify the solution if the tree had duplicate values?
What if the input arrays were very large? How would you optimize memory usage?
You can find the full solution here.