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
|
class Solution { int[] preorder; int[] inorder; Map<Integer, Integer> map = new HashMap<>();
public TreeNode buildTree(int[] preorder, int[] inorder) { this.preorder = preorder; this.inorder = inorder; int n = inorder.length; for (int i = 0; i < n; ++i) { map.put(inorder[i], i); } return build(0, n - 1, 0, n - 1); }
private TreeNode build(int preorderLeft, int preorderRight, int inorderLeft, int inorderRight) { if (preorderLeft > preorderRight) return null; int inorderRoot = map.get(preorder[preorderLeft]); TreeNode root = new TreeNode(preorder[preorderLeft]); int leftSubTreeSize = inorderRoot - inorderLeft; root.left = build(preorderLeft + 1, preorderLeft + leftSubTreeSize, inorderLeft, inorderRoot - 1); root.right = build(preorderLeft + leftSubTreeSize + 1, preorderRight, inorderRoot + 1, inorderRight); return root; } }
|