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
| /** * 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 buildTree(int[] inorder, int[] postorder) { int n1 = inorder.length; int n2 = postorder.length; Map<Integer, Integer> inorderMap = new HashMap<>(n1); for (int i = 0; i < n1; i++) { inorderMap.put(inorder[i], i); } return this.dfs(postorder, inorderMap, 0, n2 - 1, 0, n1 - 1); }
private TreeNode dfs(int[] postorder, Map<Integer, Integer> inorderMap, int postLeft, int postRight, int inLeft, int inRight) { if (postLeft > postRight) { return null; } TreeNode node = new TreeNode(postorder[postRight]); int inMid = inorderMap.get(postorder[postRight]); int postMid = postRight - inRight + inMid; node.left = dfs(postorder, inorderMap, postLeft, postMid - 1, inLeft, inMid - 1); node.right = dfs(postorder, inorderMap, postMid, postRight - 1, inMid + 1, inRight); return node; } }
|