题目:

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

思路:

总是取中间点为root

package bst;

public class ConvertSortedArrayToBinarySearchTree {

    public TreeNode sortedArrayToBST(int[] nums) {
        return constructBST(nums, 0, nums.length - 1);
    }

    private TreeNode constructBST(int[] nums, int start, int end) {
        if (start > end) return null;
        int mid = (end - start) / 2 + start;
        TreeNode root = new TreeNode(nums[mid]);
        root.left = constructBST(nums, start, mid - 1);
        root.right = constructBST(nums, mid + 1, end);
        return root;
    }
    
}

 

相关文章:

  • 2021-05-26
  • 2021-06-13
  • 2021-08-01
  • 2022-12-23
  • 2021-12-27
猜你喜欢
  • 2021-05-31
  • 2021-12-23
  • 2021-10-20
  • 2021-10-08
  • 2021-11-13
  • 2021-07-06
相关资源
相似解决方案