题目

https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/

Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.

A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.

 

Example 1:

Input: nums = [-10,-3,0,5,9]
Output: [0,-3,9,-10,null,5]
Explanation: [0,-10,5,null,-3,null,9] is also accepted:

Example 2:

Input: nums = [1,3]
Output: [3,1]
Explanation: [1,3] and [3,1] are both a height-balanced BSTs.

 

思路

二叉搜索树:中序遍历生成的数组就是升序排列的

因为 depth of the two subtrees of every node never differs by more than one.高度差不超过1

我们以中间作为根节点,这样能尽量平衡,分成左右俩部分dfs即可

1 2 【3】 4 5

1 2 3 【4】 5 6 

代码

 

class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        if (nums.length==0){
            return null;
        }
        return fun(nums,0,nums.length-1);
    }

    public TreeNode fun(int[] nums,int left,int right){
        if(left>right)
            return null;
        int mid=left+(right-left)/2;//找到根节点
        TreeNode root=new TreeNode(nums[mid]);
        //分成两个部分,[left,根节点-1][根节点+1,right]
        root.left=fun(nums,left,mid-1);
        root.right=fun(nums,mid+1,right);
        
        return root;
    }
}

 

 posted on 2021-12-05 07:48  alau  阅读(22)  评论(0编辑  收藏  举报