时月oe

博客园 首页 新随笔 联系 订阅 管理

(题目链接)[]https://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree/]

/**
 * 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 solve(nums,0,nums.length - 1);
    }
    public TreeNode solve(int[] nums,int l,int r){
        if(l > r){
            return null;
        }

        int mid = r - ((r - l) / 2);
        TreeNode root = new TreeNode(nums[mid]);
        root.left = solve(nums,l,mid - 1);
        root.right = solve(nums,mid + 1,r);

        return root;
    }
}

数组是有序的,为了构造平衡二叉树,我们每次都取中间的数作为root结点的值

posted on 2022-03-01 20:28  时月oe  阅读(19)  评论(0编辑  收藏  举报