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
  • 相关阅读:
    Windows SDK编程(Delphi版) 之 应用基础,楔子
    一个小问题引发的论证思考
    Delphi 组件开发教程指南(7)继续模拟动画显示控件
    用PyInstaller将python转成可执行文件exe笔记
    使用 .Net Memory Profiler 诊断 .NET 应用内存泄漏(方法与实践)
    Microsof Office SharePoint 2007 工作流开发环境搭建
    How to monitor Web server performance by using counter logs in System Monitor in IIS
    LINQ之Order By
    window 性能监视器
    内存泄露检测工具
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8565405.html
Copyright © 2011-2022 走看看