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

 

posted @ 2018-03-14 10:06  苗妙苗  阅读(179)  评论(0编辑  收藏  举报