108. Convert Sorted Array to Binary Search Tree(将有序数组转换为二叉搜索树)

题目链接:https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/

思路:

递归,二分确定root节点,然后确定左右子树。

AC 0ms Java:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        if(nums.length==0)
            return null;
        TreeNode head=helper(nums,0,nums.length-1);
        return head;
    }
    public TreeNode helper(int[] nums,int start,int end){
        if(start>end)
            return null;
        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;
    }
}

猜你喜欢

转载自blog.csdn.net/God_Mood/article/details/88702693
今日推荐