-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC108.java
More file actions
39 lines (32 loc) · 997 Bytes
/
Copy pathLC108.java
File metadata and controls
39 lines (32 loc) · 997 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
38
39
/**
* 108. Convert Sorted Array to Binary Search Tree
*
* Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.
*/
// Definition for a binary tree node.
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
return buildTree(nums, 0, nums.length - 1);
}
private TreeNode buildTree(int[] numArr, int left, int right) {
if(left > right) return null;
int mid = left + (right - left) / 2;
TreeNode root = new TreeNode(numArr[mid]);
root.left = buildTree(numArr, left, mid-1);
root.right = buildTree(numArr, mid+1, right);
return root;
}
}
//Solved