1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| public TreeNode buildTree(int[] preorder, int[] inorder) { if(preorder.length ==0) return null; return buildRecursion(preorder, inorder, 0, 0, preorder.length - 1); }
public TreeNode buildRecursion(int[] preorder, int[] inorder, int index, int l, int r) { int rootVal = preorder[index]; int index2 = 0; for (; rootVal != inorder[index2]; index2++) ; TreeNode root = new TreeNode(inorder[index2]); TreeNode left = null, right = null; if (index2 > l) left = buildRecursion(preorder, inorder, index + 1, l, index2 - 1); if (index2 < r) right = buildRecursion(preorder, inorder, index + (index2 - l) + 1, index2 + 1, r); root.left = left; root.right = right; return root; }
|