forked from DreamCats/java-notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathT4.java
More file actions
29 lines (26 loc) · 723 Bytes
/
Copy pathT4.java
File metadata and controls
29 lines (26 loc) · 723 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
/**
* @program JavaBooks
* @description: 将有序数组转成二叉搜索树
* @author: mf
* @create: 2020/03/09 17:06
*/
package subject.tree;
public class T4 {
/**
* 中序逆遍历
* @param nums
* @return
*/
public TreeNode sortedArrayToBST(int[] nums) {
return nums == null ? null : buildTreee(nums, 0, nums.length - 1);
}
public TreeNode buildTreee(int[] nums, int l, int r) {
if (l > r) return null;
int m = l + (r - l) / 2;
// left -> root -> right
TreeNode root = new TreeNode(nums[m]); // new一个root
root.left = buildTreee(nums, l, m - 1);
root.right = buildTreee(nums, m + 1, r);
return root;
}
}