卖萌的弱渣

I am stupid, I am hungry.

Convert Sorted Array to Binary Search Tree

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

Solution

(Convert-Sorted-Array-to-Binary-Search-Tree.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def sortedArrayToBST(self, nums):
        """
        :type nums: List[int]
        :rtype: TreeNode
        """
        if not nums:
            return None
        n = len(nums)
        index = n/2
        root = TreeNode(nums[index])
        root.left = self.sortedArrayToBST(nums[:index])
        root.right = self.sortedArrayToBST(nums[index+1:])
        return root
  • Java:
(Convert-Sorted-Array-to-BST.java) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
 *  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) {
            int n = nums.length;
            if (n==0)
                return null;
            TreeNode root = new TreeNode(nums[n/2]);
            root.left = sortedArrayToBST(Arrays.copyOfRange(nums,0,n/2));
            root.right = sortedArrayToBST(Arrays.copyOfRange(nums,n/2+1,n));
            return root;
        }
}