0
点赞
收藏
分享

微信扫一扫

Day56 将有序数组转换为二叉搜索树

给你一个整数数组 nums ,其中元素已经按 升序 排列,请你将其转换为一棵 高度平衡 二叉搜索树

高度平衡 二叉树是一棵满足「每个节点的左右两个子树的高度差的绝对值不超过 1 」的二叉树

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

示例1:

示例2:

提示:

Java解法

package sj.shimmer.algorithm.m3_2021;

import sj.shimmer.algorithm.TreeNode;

/**
 * Created by SJ on 2021/3/22.
 */

class D56 {
    public static void main(String[] args) {
        TreeNode treeNode = sortedArrayToBST(new int[]{-10, -3, 0, 5, 9});
        TreeNode.getIntegerArray(treeNode);
    }
    public static TreeNode sortedArrayToBST(int[] nums) {

        return sortedArrayToBST(nums,0,nums.length-1);
    }
    public static TreeNode sortedArrayToBST(int[] nums,int start,int end) {
        TreeNode root = null;
        if (start<=end) {
            int mid = (start + end) / 2;
            root = new TreeNode(nums[mid]);
            root.left= sortedArrayToBST(nums,start,mid-1);
            root.right= sortedArrayToBST(nums,mid+1,end);
        }
        return root;
    }
}

官方解

https://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree/solution/jiang-you-xu-shu-zu-zhuan-huan-wei-er-cha-sou-s-33/

  1. 中序遍历,总是选择中间位置左边的数字作为根节点

    • 时间复杂度: O(n)
    • 空间复杂度:O(logn)
  2. 中序遍历,总是选择中间位置右边的数字作为根节点

  3. 中序遍历,选择任意一个中间位置数字作为根节点

举报

相关推荐

0 条评论