• 530. Minimum Absolute Difference in BST 530. 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).


    BST一般都是中序,不然也没必要出BST的题了啊

    打印。这里怎么去和别的所有节点、包括之前的取得联系呢?这个地方我觉得挺困难的。
    就是prev = root;就行了,具体的迭代不用管

    TreeNode prev = root; 比较完了再更改

    Math.abs(root.val - prev.val)); 而且要用绝对值啊!

    
    
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode() {}
     *     TreeNode(int val) { this.val = val; }
     *     TreeNode(int val, TreeNode left, TreeNode right) {
     *         this.val = val;
     *         this.left = left;
     *         this.right = right;
     *     }
     * }
     */
    class Solution {
        int result = Integer.MAX_VALUE;
        TreeNode prev = new TreeNode(0);
        
        public int getMinimumDifference(TreeNode root) {
            //cc
            if (root == null) {
                return 0;
            }
            
            getMinimumDifference(root.left);
            
            
            if (Math.abs(root.val - prev.val) < result) {
                result = Math.abs(root.val - prev.val);
            }
            
            prev = root;
    
            getMinimumDifference(root.right);
            
            return result;
        }
    }
    View Code
    
    
    
    
    
  • 相关阅读:
    iOS开发官方文档汇总
    Hadoop安装配置手册
    访问.Net程序集、COM和WMI
    UML用例图教程详解
    JIRA的详细安装和破解
    [转]编程经典好书分类
    走向资深架构师的旅程
    12款响应式 Lightbox(灯箱)效果插件
    ASP.NET MVC应用程序的安全性介绍总括
    MapReduce篇之InputFormat
  • 原文地址:https://www.cnblogs.com/immiao0319/p/12945951.html
Copyright © 2020-2023  润新知