-
Notifications
You must be signed in to change notification settings - Fork 1
/
108.将有序数组转换为二叉搜索树.java
62 lines (60 loc) · 1.55 KB
/
108.将有序数组转换为二叉搜索树.java
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
* @lc app=leetcode.cn id=108 lang=java
*
* [108] 将有序数组转换为二叉搜索树
*
* https://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree/description/
*
* algorithms
* Easy (65.51%)
* Likes: 233
* Dislikes: 0
* Total Accepted: 29.5K
* Total Submissions: 44.3K
* Testcase Example: '[-10,-3,0,5,9]'
*
* 将一个按照升序排列的有序数组,转换为一棵高度平衡二叉搜索树。
*
* 本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。
*
* 示例:
*
* 给定有序数组: [-10,-3,0,5,9],
*
* 一个可能的答案是:[0,-3,9,-10,null,5],它可以表示下面这个高度平衡二叉搜索树:
*
* 0
* / \
* -3 9
* / /
* -10 5
*
*
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
return sortedArrayToBST(nums, 0, nums.length - 1);
}
private TreeNode sortedArrayToBST(int[] nums, int start, int end) {
if (start > end) {
return null;
}
int mid = (end + start + 1) / 2;
TreeNode root = new TreeNode(nums[mid]);
if (start == end) {
return root;
}
root.left = sortedArrayToBST(nums, start, mid - 1);
root.right = sortedArrayToBST(nums, mid + 1, end);
return root;
}
}