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
  • 相关阅读:
    [ios] 响应上下左右滑动手势
    [ios]字符串转化成NSDate类型 计算与当前时间的相差 月数 天数 【转】
    [ios] NSSet,NSMutableSet[zhuan]
    [ios] 如何让xcode自动检查内存泄露 【转】
    iOS 使用Quartz 2D画虚线 【转】
    [ios]设置表格单元格交替背景 【转】
    [ios] IOS文件操作的两种方式:NSFileManager操作和流操作【转】
    [ios] 自定义UIAlertView样式,实现可替换背景和按钮 【转】
    [ios]上传应用程序到app store 【转】
    [ios] iOS中arc的设置与使用
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8565405.html
Copyright © 2011-2022 走看看