zoukankan      html  css  js  c++  java
  • 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).
    

    Note: There are at least two nodes in this BST.

     1 /**
     2  * Definition for a binary tree node.
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 public class Solution {
    11     int min = Integer.MAX_VALUE;
    12     Integer prev = null;
    13     
    14     public int getMinimumDifference(TreeNode root) {
    15         if (root == null) return min;
    16         
    17         getMinimumDifference(root.left);
    18         
    19         if (prev != null) {
    20             min = Math.min(min, root.val - prev);
    21         }
    22         prev = root.val;
    23         
    24         getMinimumDifference(root.right);
    25         
    26         return min;
    27     }
    28     
    29 }
     
  • 相关阅读:
    Twitter视频下载方式
    维基百科镜像处理
    Python sll
    youyube-dl
    python 进程池pool
    python常用正则表达式
    Struts2笔记3--OGNL
    Struts2笔记2
    Struts2笔记1
    Hibernate笔记7--JPA CRUD
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/6480751.html
Copyright © 2011-2022 走看看