• [LeetCode] 108. Convert Sorted Array to Binary Search Tree


    Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.

    A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.

    Example 1:

    Input: nums = [-10,-3,0,5,9]
    Output: [0,-3,9,-10,null,5]
    Explanation: [0,-10,5,null,-3,null,9] is also accepted:
    

    Example 2:

    Input: nums = [1,3]
    Output: [3,1]
    Explanation: [1,3] and [3,1] are both a height-balanced BSTs.

    Constraints:

    • 1 <= nums.length <= 104
    • -104 <= nums[i] <= 104
    • nums is sorted in a strictly increasing order.

    将有序数组转化为二叉搜索树。

    题目即是题意。只要输出一个有效的BST即可。此题可以跟109题一起做,要求很接近但是做法不太一样。

    这个题可以用递归做。因为是BST的关系,而且input是有序数组,如果熟练,就会想到中序遍历BST的output就是一个有序数组。思路是找到数组的mid元素,即是找到了BST的根节点。小于根节点的节点是左孩子,反之是右孩子。但是注意中序遍历的结果并不能确定唯一的BST。代码如下

    时间O(n)

    空间O(n)

    Java实现

     1 class Solution {
     2     public TreeNode sortedArrayToBST(int[] nums) {
     3         // corner case
     4         if (nums == null || nums.length == 0) {
     5             return null;
     6         }
     7         return helper(nums, 0, nums.length - 1);
     8     }
     9 
    10     private TreeNode helper(int[] nums, int left, int right) {
    11         if (left > right)
    12             return null;
    13         int mid = left + (right - left) / 2;
    14         TreeNode root = new TreeNode(nums[mid]);
    15         root.left = helper(nums, left, mid - 1);
    16         root.right = helper(nums, mid + 1, right);
    17         return root;
    18     }
    19 }

    JavaScript实现

     1 /**
     2  * @param {number[]} nums
     3  * @return {TreeNode}
     4  */
     5 var sortedArrayToBST = function (nums) {
     6     if (nums == null || nums.length == 0) return null;
     7     return helper(nums, 0, nums.length - 1);
     8 }
     9 
    10 var helper = function (nums, low, high) {
    11     if (low > high) return null;
    12     var mid = parseInt((high + low) / 2);
    13     var root = new TreeNode(nums[mid]);
    14     root.left = helper(nums, low, mid - 1);
    15     root.right = helper(nums, mid + 1, high);
    16     return root;
    17 }

    相关题目

    108. Convert Sorted Array to Binary Search Tree

    109. Convert Sorted List to Binary Search Tree

    1382. Balance a Binary Search Tree

    LeetCode 题目总结

  • 相关阅读:
    为什么ip层收到的报文可能已经设置了路由
    由socket fd泄漏想到的一些问题
    Html.DropDownLis绑定数据库
    CSS 属性备注
    获取IP
    读取TXT并筛选数据写入新建TXT
    C#打印图片
    C#生成二维码
    NPOI操作Excel
    Bootstrap
  • 原文地址:https://www.cnblogs.com/cnoodle/p/12293678.html
Copyright © 2020-2023  润新知