108-Convert Sorted Array to Binary Search Tree

kevin聰發表於2018-05-02

Description

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

問題描述

給定一個元素為遞增序列的陣列, 將其轉換為平衡二叉排序樹

平衡二叉排序樹定義為, 每個節點的左右子樹的高度之差不大於1


問題分析

每次取陣列的中間元素作為當前節點即可


解法

public class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        if(nums == null || nums.length == 0)    return null;

        return getTreeNode(nums, 0, nums.length - 1);
    }
    private TreeNode getTreeNode(int[] nums, int start, int end){
        //注意這裡
        if(start > end)    return null;
        //取中間元素作為當前節點
        int middle = start + (end - start) / 2;
        TreeNode n = new TreeNode(nums[middle]);
        //注意start和end的變化
        n.left = getTreeNode(nums, start, middle - 1);
        n.right = getTreeNode(nums, middle + 1, end);

        return n;
    }
}

相關文章