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