108. Convert Sorted Array to Binary Search Tree / 109. Convert Sorted List to Binary Search Tree

108. Convert Sorted Array to Binary Search Treearrow-up-right

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

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example:

Given the sorted array: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

      0
     / \
   -3   9
   /   /
 -10  5

My Solutions:

找到sorted array中点作为root,root.left是root左边的数,root.left 是root右边的数

class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        if (nums == null) return null;
        return helper(nums, 0, nums.length - 1);
    }
    
    private TreeNode helper(int[] nums, int start, int end) {
        if (start > end) return null;
        TreeNode node = new TreeNode(nums[(start + end) / 2]);
        node.left = helper(nums, start, (start + end) / 2 - 1);
        node.right = helper(nums, (start + end) / 2 + 1, end);
        return node;
    }
}

109. Convert Sorted List to Binary Search Tree

My Solutions:

和108类似,找到list的中点作为root。

Last updated