zoukankan      html  css  js  c++  java
  • 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
    
    
    
    
    
  • 相关阅读:
    改进RazorPad
    ViewBag、ViewData和TempData的使用和区别
    MVC3路由设置访问后缀 html jsp
    RazorPad中的ModelProvider
    使用NUnit进行项目的单元测试
    有关WCF的契约问题
    常用的Windows批处理
    SmartBusinessDevFramework架构设计-2:结构图示
    SQL中查询语句的使用
    林子祥
  • 原文地址:https://www.cnblogs.com/immiao0319/p/12945951.html
Copyright © 2011-2022 走看看