Convert Sorted Array to Binary Search Tree数组变成高度平衡的二叉树

[抄题]:

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.


Example:

Given the sorted array: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

      0
     / 
   -3   9
   /   /
 -10  5

 [暴力解法]:

时间分析:

空间分析:

[奇葩输出条件]:

把数字转成node时,把数字当成node中的参数,表示节点里的值

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

[奇葩corner case]:

TreeNode node = new TreeNode(0) 形成的是0节点 有东西,所以数组长为0时应该输出null, 没有东西

[思维问题]:

以为建立节点可以参数化:不能,节点的建立只能用赋值。头一次见

[一句话思路]:

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

  1. 上下限参数把没用的left right都放进去了。不能,应该只放相关的。左子树放左边的上下限,右子树放右边的上下限
  2. 0 和 length -1 搭配,每次都要提前注意

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

[复杂度]:Time complexity: O(n) Space complexity: O(n)

[英文数据结构或算法,为什么不用别的数据结构或算法]:

左右同时进行挖底一直进行,高度不超过1,用dfs

[关键模板化代码]:

public TreeNode helper(int[] nums, int low, int high) {      
    //corner case : low > high
        if (low > high) {
            return null;
        }
        int mid = low + (high - low) / 2;
        TreeNode root = new TreeNode(nums[mid]);
        
        root.left = helper(nums, low, mid - 1);
        root.right = helper(nums, mid + 1, high);
        
        return root;
    }
helper嵌套

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

 [代码风格] :

/**
 * 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) {
        TreeNode node = new TreeNode(0);
        //corner case
        if (nums.length == 0) {
            return node;
        }
        node = helper(nums, 0, nums.length - 1);// -1 should be noticed ahead
        return node;
    }
    
    public TreeNode helper(int[] nums, int low, int high) {      
    //corner case : low > high
        if (low > high) {
            return null;
        }
        int mid = low + (high - low) / 2;
        TreeNode root = new TreeNode(nums[mid]);
        
        root.left = helper(nums, low, mid - 1);
        root.right = helper(nums, mid + 1, high);
        
        return root;
    }
}
View Code
原文地址:https://www.cnblogs.com/immiao0319/p/8547536.html