/**
- 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;
- }
- }
*/
class Solution {
Map<Integer, Integer> hm = new HashMap<>();
public TreeNode buildTree(int[] inorder, int[] postorder) {
for (int i = 0; i < inorder.length; ++i) {
hm.put(inorder[i], i);
}
return dfs(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1);
}
TreeNode dfs(int[] in, int il, int ir, int[] post, int pl, int pr) {
if (il > ir) {
return null;
}
int k = hm.get(post[pr]);
TreeNode node = new TreeNode(post[pr]);
node.left = dfs(in, il, k - 1, post, pl, pl + k - 1 - il);
node.right = dfs(in, k + 1, ir, post, pl + k - il, pr - 1);
return node;
}
}