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 { public TreeNode buildTree(int[] preorder, int[] inorder) { return buildTree(preorder, 0, inorder, 0, inorder.length); }
public TreeNode buildTree(int[] preorder, int rootIdx, int[] inorder, int start, int end) { if (start >= end) { return null; }
if (start == end - 1) { return new TreeNode(inorder[start]); }
TreeNode root = new TreeNode(preorder[rootIdx]);
int rootIdxInOrder = start; for (int idx = start; idx < end; idx++) { if (inorder[idx] == root.val) { rootIdxInOrder = idx; break; } }
TreeNode leftNode = buildTree(preorder, rootIdx + 1, inorder, start, rootIdxInOrder);
TreeNode rightNode = buildTree(preorder, rootIdx + 1 + rootIdxInOrder - start, inorder, rootIdxInOrder + 1, end);
root.left = leftNode; root.right = rightNode; return root; } }
|