106. Construct Binary Tree from Inorder and Postorder Traversal
#Problem description:
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
inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]
Return the following binary tree:
3
/ \
9 20
/ \
15 7
#Solution:
This problem is pretty similar to 105. Construct Binary Tree from Preorder and Inorder Traversal.
We can see the inorder and postorder array like this:1
2
3
4
5
6
7
8
9 in order
+------------+------+-------------+
| left child | root | right child |
+------------+------+-------------+
post order
+------------+-------------+------+
| left child | right child | root |
+------------+-------------+------+
As you can see, root
is in the last position in postorder
array. After we find the root, we can get the length of each subarray as follows:
- left tree:
inOrder[1 .. p - 1]
postOrder[1 .. p - 1] - right tree:
inOrder[p + 1 .. n]
postOrder[p .. n - 1]
1 | /** |