Convert Sorted Array to Binary Search Tree

Description

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

Method

1.将字符串的中间值设为头结点并返回这个头结点。

2.对中间值左边的数组重复1的操作,并作为头结点的左节点返回。

3.对中间值右边的数组重复1的操作,并作为头结点的右节点返回。

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
* 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 == 0) return null;
return makeTree(nums, 0, nums.length - 1);
}

public TreeNode makeTree(int[] nums, int start, int end){
if(end < start) return null;
int mid = start + (end - start)/2;
TreeNode node = new TreeNode(nums[mid]);
node.right = makeTree(nums, mid + 1, end);
node.left = makeTree(nums, start, mid - 1);
return node;
}
}