zoukankan      html  css  js  c++  java
  • 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

    1. 中间的index不是除以2,而是mid = low + (high - low) / 2;
    2. 初始化节点: TreeNode node = new TreeNode(0);
      和改变节点:node = helper(nums, 0, nums.length - 1);
      是两个步骤的时候,就要用helper函数

    3. 好吧,原来高度不超过1是通过index来控制的,也是把左右当做参数:左边一个右边一个

     

    node.left =
    node.right =
    都是在helper中完成的,helper可以多功能一些
    helper中也有边界条件

    而且用了数组的话,函数的参数最好带上数组名

    自己写的,不知道里面为啥会链表有环

    class Solution {
        public TreeNode sortedArrayToBST(int[] nums) {
            //特殊情况
            if (nums.length < 0 || nums == null) 
                return null;
            
            TreeNode root = new TreeNode(0);
            return helper(root, nums, 0, nums.length - 1);
        }
        
        TreeNode helper(TreeNode node, int[] nums, int left, int right) {
            //特殊情况
            if (left > right) {
                return null;
            }
            
            int mid = left + (right - left) / 2;
            node.left = helper(node, nums, left, mid - 1);
            node.right = helper(node, nums, mid + 1, right);
                
            return node;
        }
    }
    View Code

     正确版本

    class Solution {
        public TreeNode sortedArrayToBST(int[] nums) {
            //特殊情况
            if (nums.length < 0 || nums == null) 
                return null;
            
            TreeNode root = new TreeNode(0);
            return helper(nums, 0, nums.length - 1);
        }
        
        TreeNode helper(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 = helper(nums, left, mid - 1);
            node.right = helper(nums, mid + 1, right);
                
            return node;
        }
    }
    View Code

     

  • 相关阅读:
    电子海图开发一百篇第五十五篇-电子江图传输规范 数据模型
    天气可视化,海浪,温度图层的绘制,温度热力图的可视化
    全球潮汐数据API使用方法,潮汐数据查询
    海洋气象数据可视化,以流场的方式显示风场图,海洋气象API使用
    g++ 编译module失败
    编译gcc error-*** LIBRARY_PATH shouldn‘t contain the current directory when *** building gcc.
    windows两种自启动的区别
    windows多线程加锁
    windows server 2012不显示此电脑
    pthread_cond_wait
  • 原文地址:https://www.cnblogs.com/immiao0319/p/12941323.html
Copyright © 2011-2022 走看看