面试题 04.02. 最小高度树 ( 二分 )

LeetCode:面试题 04.02. 最小高度树

在这里插入图片描述

二叉搜索树 and 有序的数组

二分建树,将左区间作为左子树, 右区间作为右子树


AC Code

/**
 * 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) {
    
    
        return binaryCreate(nums, 0, nums.length - 1);
    }

    public TreeNode binaryCreate(int[] nums, int left, int right){
    
    
        if(left > right) return null;
        int mid = left + (right - left) / 2;

        TreeNode node = new TreeNode(nums[mid]);

        node.left = binaryCreate(nums, left, mid - 1);
        node.right = binaryCreate(nums, mid + 1, right);

        return node;
    }
}



猜你喜欢

转载自blog.csdn.net/qq_43765535/article/details/112803998