题目链接
思路:递归
- 本题和上道题几乎是完全一样呀,唯一的区别就是后序遍历的根节点是在最后一个
class Solution {
Map<Integer, Integer> map;
int[] postorder;
public TreeNode buildTree(int[] inorder, int[] postorder) {
map = new HashMap<>();
for (int i = 0; i < inorder.length; i++) {
map.put(inorder[i], i);
}
this.postorder = postorder;
return dfs(0, inorder.length - 1, 0, postorder.length - 1);
}
private TreeNode dfs(int inorderLeft, int inorderRight, int postorderLeft, int postorderRight) {
if (inorderLeft > inorderRight || postorderLeft > postorderRight)
return null;
TreeNode root = new TreeNode(postorder[postorderRight]);
int rootIndex = map.get(postorder[postorderRight]),
leftSubTreeLength = rootIndex - inorderLeft;
root.left = dfs(inorderLeft, rootIndex - 1, postorderLeft, postorderLeft + leftSubTreeLength - 1);
root.right = dfs(rootIndex + 1, inorderRight, postorderLeft + leftSubTreeLength , postorderRight - 1);
return root;
}
}