-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
39 lines (32 loc) · 957 Bytes
/
Solution.java
File metadata and controls
39 lines (32 loc) · 957 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
package com.q0108;
import com.q0101_symmetric_tree.TreeNode;
/**
* @author xjn
* @since 2020-02-16
* https://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree/
* 108. 将有序数组转换为二叉搜索树
* 时间复杂度O(n)
* 空间复杂度O(logN)
*/
public class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
return sortedArrayToBST(nums, 0, nums.length - 1);
}
private TreeNode sortedArrayToBST(int[] nums, int l, int r) {
if (nums == null) {
return null;
}
if (l > r) {
return null;
}
int mid = l + (r - l + 1) / 2;
TreeNode root = new TreeNode(nums[mid]);
TreeNode left = sortedArrayToBST(nums, l, mid - 1);
TreeNode right = sortedArrayToBST(nums, mid + 1, r);
root.left = left;
root.right = right;
return root;
}
public static void main(String[] args) {
}
}