108 Convert Sorted Array to Binary Search Tree

108. Convert Sorted Array to Binary Search Tree

1. Question

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

2. Implementation

(1) Recursion
1
class Solution {
2
public TreeNode sortedArrayToBST(int[] nums) {
3
if (nums == null || nums.length == 0) {
4
return null;
5
}
6
7
return generateBST(nums, 0, nums.length - 1);
8
}
9
10
public TreeNode generateBST(int[] nums, int start, int end) {
11
if (start > end) {
12
return null;
13
}
14
15
int mid = start + (end - start) / 2;
16
TreeNode curNode = new TreeNode(nums[mid]);
17
curNode.left = generateBST(nums, start, mid - 1);
18
curNode.right = generateBST(nums, mid + 1, end);
19
return curNode;
20
}
21
}
Copied!
(2) Iterative
1
class Solution {
2
public TreeNode sortedArrayToBST(int[] nums) {
3
if (nums == null || nums.length == 0) {
4
return null;
5
}
6
7
TreeNode root = new TreeNode(0);
8
Stack<TreeNode> nodes = new Stack<>();
9
Stack<Integer> leftIndexes = new Stack<>();
10
Stack<Integer> rightIndexes = new Stack<>();
11
12
nodes.push(root);
13
leftIndexes.push(0);
14
rightIndexes.push(nums.length - 1);
15
16
while (!nodes.isEmpty()) {
17
TreeNode curNode = nodes.pop();
18
int start = leftIndexes.pop();
19
int end = rightIndexes.pop();
20
21
int mid = start + (end - start) / 2;
22
curNode.val = nums[mid];
23
24
if (start <= mid - 1) {
25
curNode.left = new TreeNode(0);
26
nodes.push(curNode.left);
27
leftIndexes.push(start);
28
rightIndexes.push(mid - 1);
29
}
30
31
if (end >= mid + 1) {
32
curNode.right = new TreeNode(0);
33
nodes.push(curNode.right);
34
leftIndexes.push(mid + 1);
35
rightIndexes.push(end);
36
}
37
}
38
return root;
39
}
40
}
Copied!

3. Time & Space Complexity

Recursion: 时间复杂度O(n), 空间复杂度: O(logn)
Iteration: 时间复杂度O(n), 空间复杂度: O(n)