Convert Sorted Array to Binary Search Tree
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

1.解题思路
平衡二叉树,其实就是数组中间的数作为根,利用递归实现左子树和右子树的构造。

2.代码

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

tiffanytown
6 声望2 粉丝

keep learning