Problem
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
1 |
|
Return the following binary tree:
1 |
|
Explanation 1
- Similar to 105. Construct Binary Tree from Preorder and Inorder Traversal, this time, we know the root node is the end element of
postorder
array, and we can find the root element in theinorder
array, then we can know the range of leftsubtree and rightsubtree. One example is below:
1 |
|
Solution 1
1 |
|
Explanation 2
-
Using the while loop to find the root value’s index in
inorder[]
in each recursion call make the time complexity be $O(n^2)$. We can reduce the time complexity to $O(n)$ by using a HashMap to record the key is the element, value is the element’s index. -
We can also remove the
postStart
since we only need to find the root frompostorder[]
by usingpostEnd
.
Solution 2
1 |
|