Leetcode Convert Sorted Array to Binary Search Tree 有序数组转换成二叉搜索树BST


题目:


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


分析:

这道题和有序链表转换成BST的方法相同,都是用递归。 

1. 递归的结束条件是当start>=end

2. 找到数组的中点,作为根节点

3. 递归的在左半边构建左子树,右半边构建右子树


Java代码实现:


/**
 * 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) {
        if(nums==null || nums.length==0)
            return null;
            
        return helper(nums, 0, nums.length-1);
    }
    private TreeNode helper(int[] nums, int start, int end)
    {
        if(start > end)
            return null;
            
        if(start == end)
            return new TreeNode(nums[start]);
            
        int mid = (start + end)/2;
        TreeNode root = new TreeNode(nums[mid]);
        root.left = helper(nums, start, mid-1);
        root.right = helper(nums, mid+1, end);
        
        return root;
    }
}

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页