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
|
class Solution { public TreeNode buildTree(int[] preorder, int[] inorder) { if (inorder == null || preorder == null || inorder.length == 0 || preorder.length == 0) { return null; } int len = preorder.length; Map<Integer, Integer> indexMap = new HashMap<>(); for (int i = 0; i < len; i++) { indexMap.put(inorder[i], i); } return helper(inorder, preorder, 0, len - 1, 0, len - 1, indexMap); } private TreeNode helper(int[] inorder, int[] preorder, int iStart, int iEnd, int pStart, int pEnd, Map<Integer, Integer> map) { if (iStart > iEnd || pStart > pEnd) { return null; } int pivot = preorder[pStart]; TreeNode root = new TreeNode(pivot); int pivotIndex = map.get(pivot); int leftLen = pivotIndex - iStart; root.left = helper(inorder, preorder, iStart, pivotIndex - 1, pStart + 1, pStart + leftLen, map); root.right = helper(inorder, preorder, pivotIndex + 1, iEnd, pStart + leftLen + 1, pEnd, map); return root; } }
|