#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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
return deal(0, inorder.size() - 1, 0, postorder.size() - 1, inorder, postorder);
}

TreeNode* deal(int leftInorder, int rightInorder, int leftPostorder, int rightPostorder, vector<int>& inorder, vector<int>& postorder) {
if (rightInorder < leftInorder || rightPostorder < leftPostorder) return NULL;

TreeNode* rt = new TreeNode(postorder[ rightPostorder ]);

int p = 0;
for (int i = 0; i <= rightInorder - leftInorder; ++i)
if (inorder[leftInorder + i] == rt -> val) {
p = i; break;
}

rt -> left = deal(leftInorder, leftInorder + p - 1, leftPostorder, leftPostorder + p - 1, inorder, postorder);
rt -> right = deal(leftInorder + p + 1, rightInorder, leftPostorder + p, rightPostorder - 1, inorder, postorder);

return rt;
}

};