forked from tanglu/Leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconvertSortedArrayToBinarySearchTree.java
More file actions
Latest commit
37 lines (33 loc) · 970 Bytes
/
Copy pathconvertSortedArrayToBinarySearchTree.java
File metadata and controls
37 lines (33 loc) · 970 Bytes
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
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
publicclassSolution {
TreeNodebuildTree(int[] num, intbegin, intend) {
if(begin==end) {
TreeNodenode = newTreeNode(num[begin]);
returnnode;
} else {
intmid = begin + (end - begin)/2;
TreeNodenode = newTreeNode(num[mid]);
if(begin<=(mid-1)) {
node.left = buildTree(num, begin, mid - 1);
}
if((mid+1)<=end) {
node.right = buildTree(num, mid + 1, end);
}
returnnode;
}
}
publicTreeNodesortedArrayToBST(int[] num) {
if(num==null||num.length==0) {
returnnull;
}
returnbuildTree(num, 0, num.length-1);
}
}