LeetCode 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).

 

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

 


 

题目标签:Binary Search Tree

  这道题目给了我们一个二叉搜索树,其特性为 左 < 根 < 右。让我们找到树中最小的绝对差值,可以存在任意两点中。如果看到二叉搜索树,一定要条件反射性的想起用 inOrder traverse,所有的值是从小到大的排序。这样就很容易找到最小的绝对差了,对于每一个点,和之前那个点比较一下,遍历完树,就可以找到最小的差值。

 

Java Solution:

Runtime beats 77.33% 

完成日期:07/10/2017

关键词:Binary Search Tree

关键点:利用 inOrder traverse 遍历树,所有点的值排序为从小到大

 

 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 {
12     int minDiff = Integer.MAX_VALUE;
13     TreeNode preNode = null;
14     
15     public int getMinimumDifference(TreeNode root) 
16     {
17         inOrder(root);
18         return minDiff;
19     }
20     
21     public void inOrder(TreeNode node)
22     {
23         if(node == null)
24             return;
25         
26         inOrder(node.left);
27         
28         // get the diff between preNode and node
29         if(preNode != null) // because the first time preNode is null
30             minDiff = Math.min(minDiff, Math.abs(node.val - preNode.val));
31         
32         preNode = node;
33         
34         inOrder(node.right);
35     }
36 }

参考资料:

http://www.cnblogs.com/grandyang/p/6540165.html

 

LeetCode 算法题目列表 - LeetCode Algorithms Questions List

 

posted @ 2017-07-11 05:06  Jimmy_Cheng  阅读(540)  评论(0编辑  收藏  举报