106. Construct Binary Tree from Inorder and Postorder Traversal
```java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
inorder = [9,3,15,20,7],
postorder = [9,15,7,20,3]
postorder last one is root
find 3 in inorder
left is 9, right is [15, 20, 7]
build a hashmpa for inorder to find fast
T: O(n)
S: O(n)
*/
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < inorder.length; i++) {
map.put(inorder[i], i);
}
return dfs(inorder, postorder, 0, postorder.length-1, 0, inorder.length-1, map);
}
private TreeNode dfs(int[] inorder, int[] postorder, int postS, int postE, int inS, int inE, Map<Integer, Integer> map) {
if (postS > postE) {
return null;
}
int rootNumber = postorder[postE];
int rootIndex = map.get(rootNumber);
TreeNode root = new TreeNode(rootNumber);
int leftSize = rootIndex - inS;
root.left = dfs(inorder, postorder, postS, postS + leftSize - 1, inS, rootIndex-1, map); // post [left, right, root]
root.right = dfs(inorder, postorder, postS + leftSize, postE - 1, rootIndex+1, inE, map);
return root;
}
}
```
Last updated