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
tag: binary tree, DFS
/**
* 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 (inorder == null || inorder.length == 0) return null;
Map<Integer, Integer> hash = new HashMap<>();
for (int i = 0; i < inorder.length; i++){
hash.put(inorder[i], i);
}
return dfs(0, postorder.length - 1, 0, inorder.length - 1, hash, inorder, postorder);
}
private TreeNode dfs(int postStart, int postEnd, int inStart, int inEnd, Map<Integer, Integer> hash, int[] inorder, int[] postorder){
if (postStart > postEnd || inStart > inEnd) return null;
TreeNode root = new TreeNode(postorder[postEnd]);
int inIndex = hash.get(postorder[postEnd]);
root.left = dfs(postStart, postStart + inIndex - inStart - 1, inStart, inIndex - 1, hash, inorder, postorder);
root.right = dfs(postStart + inIndex - inStart, postEnd - 1, inIndex + 1, inEnd, hash, inorder, postorder);
return root;
}
}