106. Construct Binary Tree from Inorder and Postorder Traversal
Medium
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
Tips: iterate backward postorder. build tree right first, then left.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
if (null == postorder || postorder.length < 1) {
return null;
}
int[] idx = {postorder.length - 1};
return buildTree(postorder, idx, inorder, 0, inorder.length - 1);
}
private TreeNode buildTree(int[] postorder, int[] idx, int[] inorder, int s, int e) {
int rIdx = s;
for (int i = s; i <= e; i++) {
if (postorder[idx[0]] == inorder[i]) {
rIdx = i;
break;
}
}
TreeNode root = new TreeNode(postorder[idx[0]]);
//right
if (e - rIdx >= 1) {
idx[0] -= 1;
root.right = buildTree(postorder, idx, inorder, rIdx + 1, e);
}
// left
if (rIdx - s >= 1) {
idx[0] -= 1;
root.left = buildTree(postorder, idx, inorder, s, rIdx - 1);
}
return root;
}
}