1. 题目

2. 思路
(1) 递归
- 后序遍历的最后一个结点是根结点,在中序遍历中定位根结点的位置,则中序遍历中根结点的左边均为左子树结点,右边均为右子树结点,递归构建左右子树即可。
- 定位根结点的位置可以利用HashMap。
3. 代码
import java.util.HashMap;
import java.util.Map;
public class Test {
public static void main(String[] args) {
}
}
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 {
private int[] postorder;
private Map<Integer, Integer> map;
public TreeNode buildTree(int[] inorder, int[] postorder) {
this.postorder = postorder;
map = new HashMap<>();
for (int i = 0; i < inorder.length; i++) {
map.put(inorder[i], i);
}
return recur(0, inorder.length - 1, 0, postorder.length - 1);
}
private TreeNode recur(int inLeft, int inRight, int postLeft, int postRight) {
if (inLeft > inRight) {
return null;
}
TreeNode root = new TreeNode(postorder[postRight]);
int mid = map.get(postorder[postRight]);
int leftCount = mid - inLeft;
root.left = recur(inLeft, inLeft + leftCount - 1, postLeft, postLeft + leftCount - 1);
root.right = recur(mid + 1, inRight, postLeft + leftCount, postRight - 1);
return root;
}
}