p108

LeetCode p108 Convert Sorted Array to Binary Search Tree 题解

1.题目:

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

题意:

输入一个数组将它转换为二叉平衡查找树。

2.解题思路:

dp取中间~一步步将树拓展开来。

3.代码


[title] [] [url] [link text]
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
 
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if (nums.length < 1)
return null;
if (nums.length == 1) {
return new TreeNode(nums[0]);
}
int len = nums.length;
TreeNode tNode = new TreeNode(nums[len / 2]);
dp(nums, 0, len / 2 - 1, tNode, true);
dp(nums, len / 2 + 1, len - 1, tNode, false);
return tNode;
}

public void dp(int[] nums, int left, int right, TreeNode tNode,
boolean l) {

if (left > right)
return;
int mid = (right - left) / 2 + left;
TreeNode t = new TreeNode(nums[mid]);
if (l) {
System.out.println("left" + t.val);
tNode.left = t;
} else {
System.out.println("right" + t.val);
tNode.right = t;
}
dp(nums, left, mid - 1, t, true);
dp(nums, mid + 1, right, t, false);

}
}


4.一些总结: