您的位置:首页 > Web前端

LeetCode 530. Minimum Absolute Difference in BST (二叉搜索树中最小绝对差)

2017-07-11 05:06 507 查看

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 遍历树,所有点的值排序为从小到大

 

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution
{
int minDiff = Integer.MAX_VALUE;
TreeNode preNode = null;

public int getMinimumDifference(TreeNode root)
{
inOrder(root);
return minDiff;
}

public void inOrder(TreeNode node)
{
if(node == null)
return;

inOrder(node.left);

// get the diff between preNode and node
if(preNode != null) // because the first time preNode is null
minDiff = Math.min(minDiff, Math.abs(node.val - preNode.val));

preNode = node;

inOrder(node.right);
}
}

参考资料:

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

 

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

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: