zoukankan      html  css  js  c++  java
  • 530.Minimum Absolute Difference in BST 二叉搜索树中的最小差的绝对值

    [抄题]:

    Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.

    Example:

    Input:
    
       1
        
         3
        /
       2
    
    Output:
    1
    
    Explanation:
    The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).
    

     [暴力解法]:

    时间分析:

    空间分析:

    [奇葩输出条件]:

    [奇葩corner case]:

    [思维问题]:

    基础弱到忘了二叉树的traverse怎么写了,还以为要输出到array

    [一句话思路]:

    先初始化为MAX_VALUE,再按标准格式写

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

    [画图]:

    [一刷]:

    1. traverse函数里面切勿定义变量,会导致重复赋值出错。以前错了没注意
    2. 四则运算的对象也要满足非空not null 的基本条件

    [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

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

    [总结]:

    先初始化为MAX_VALUE,再按标准格式写

    [复杂度]:Time complexity: O(n) Space complexity: O(1) 没有额外空间

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

    [关键模板化代码]:

    左中右

    getMinimumDifference(root.left);
            
            if (prev != null) {
                min = Math.min(min, root.val - prev);
            }
            prev = root.val;
            
            getMinimumDifference(root.right);

    [其他解法]:

    [Follow Up]:

     不是BST,用treeset,复杂度都是lgn,可以取出任何一个元素

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

     [代码风格] :

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        int min = Integer.MAX_VALUE;
        TreeNode prev = null;
        
        public int getMinimumDifference(TreeNode root) {
            //corner case
            if (root == null) {
                return min;
            }
            //in-order traversal
            getMinimumDifference(root.left);
            if (prev != null) {//only deletable if not null
                min = Math.min(min, root.val - prev.val);
            }
            //refresh the prev
            prev = root;
            getMinimumDifference(root.right);
            //return
            return min;
        }
    }
    View Code
  • 相关阅读:
    VirtualBox 收缩 vdi镜像文件
    虚拟机安装Lubuntu
    做一个平均数,合计数的sql查询
    postgersql 中 字段名,表名,命名大小写问题(原创)
    你人生中的那口井挖了没有?(转潇湘隐者)
    【智能无线小车系列十一】智能小车一体化测试
    【智能无线小车系列二】车体的组装
    【智能无线小车系列一】物品采购
    【智能无线小车系列十】通过USB摄像头实现网络监控功能
    【智能无线小车系列九】在树莓派上使用USB摄像头
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8565405.html
Copyright © 2011-2022 走看看