1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| /** * 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 { public TreeNode constructFromPrePost(int[] preorder, int[] postorder) { int n1 = preorder.length; int n2 = postorder.length; Map<Integer, Integer> postIndexMap = new HashMap<>(n2); for (int i = 0; i < n2; i++) { postIndexMap.put(postorder[i], i); } return this.dfs(preorder, postIndexMap, 0, n1 - 1, 0, n2 - 1); }
private TreeNode dfs(int[] preorder, Map<Integer, Integer> postIndexMap, int preLeft, int preRight, int postLeft, int postRight) { if (preLeft > preRight) { return null; } TreeNode root = new TreeNode(preorder[preLeft]); if (preLeft < preRight) { int postMid = postIndexMap.get(preorder[preLeft + 1]); int preMid = preLeft + postMid - postLeft + 1; root.left = this.dfs(preorder, postIndexMap, preLeft + 1, preMid, postLeft, preMid); root.right = this.dfs(preorder, postIndexMap, preMid + 1, preRight, postMid + 1, postRight - 1); } return root; } }
|