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

 

思路:

// @Title: 将有序数组转换为二叉搜索树 (Convert Sorted Array to Binary Search Tree)
// @Author: qisiii
// @Date: 2024-09-16 18:35:37
// @Runtime: 0 ms
// @Memory: 42.3 MB
// @comment: 
// @flag: 
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        return doBST(nums,0,nums.length-1);
    }

    private TreeNode doBST(int[] nums,int left,int right){
        if(left>right){
            return null;
        }
        int mid=left+(right-left)/2;
        TreeNode root=new TreeNode(nums[mid]);
        root.left=doBST(nums,left,mid-1);
        root.right=doBST(nums,mid+1,right);
        return root;
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18