Skip to content

Commit 4f6bf5e

Browse files
author
applewjg
committed
add inorder solution
Change-Id: I845e188989bfd6ba1f59f4ad1bf6992023220b57
1 parent b9f7dfb commit 4f6bf5e

File tree

1 file changed

+19
-2
lines changed

1 file changed

+19
-2
lines changed

ConvertSortedArraytoBinarySearchTree.java

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,10 @@
77
Notes:
88
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
99
10-
Solution: Recursion.
10+
Solution: Recursion. 1. preorder
11+
2. inorder
1112
*/
13+
1214
/**
1315
* Definition for binary tree
1416
* public class TreeNode {
@@ -19,7 +21,7 @@
1921
* }
2022
*/
2123
public class Solution {
22-
public TreeNode sortedArrayToBST(int[] num) {
24+
public TreeNode sortedArrayToBST_1(int[] num) {
2325
return sortedArrayToBSTRe(num, 0, num.length - 1);
2426
}
2527
public TreeNode sortedArrayToBSTRe(int[] num, int left, int right) {
@@ -31,4 +33,19 @@ public TreeNode sortedArrayToBSTRe(int[] num, int left, int right) {
3133
node.right = sortedArrayToBSTRe(num, mid + 1, right);
3234
return node;
3335
}
36+
public TreeNode sortedArrayToBST(int[] num) {
37+
int[] curidx = new int[1];
38+
curidx[0] = 0;
39+
return sortedArrayToBSTRe1(num, num.length, curidx);
40+
}
41+
public TreeNode sortedArrayToBSTRe1(int[] num, int len, int[] curidx) {
42+
if (len == 0) return null;
43+
if (len == 1) return new TreeNode(num[curidx[0]++]);
44+
int mid = len / 2;
45+
TreeNode left = sortedArrayToBSTRe1(num, mid, curidx);
46+
TreeNode node = new TreeNode(num[curidx[0]++]);
47+
node.left = left;
48+
node.right = sortedArrayToBSTRe1(num, len - 1 - mid, curidx);
49+
return node;
50+
}
3451
}

0 commit comments

Comments
 (0)