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
相关文章推荐
- [LeetCode] Minimum Absolute Difference in BST 二叉搜索树的最小绝对差
- leetcode Minimum Absolute Difference in BST 二叉搜索树中的最小差
- [LeetCode]530. Minimum Absolute Difference in BST(BST的最小绝对差)
- leetcode 530. Minimum Absolute Difference in BST
- 【Leetcode】530. Minimum Absolute Difference in BST
- LeetCode530. Minimum Absolute Difference in BST
- LeetCode 530. Minimum Absolute Difference in BST
- leetcode-530. Minimum Absolute Difference in BST
- Leetcode-530. Minimum Absolute Difference in BST
- leetcode-530. Minimum Absolute Difference in BST
- LeetCode - 530. Minimum Absolute Difference in BST
- [LeetCode]530. Minimum Absolute Difference in BST
- Leetcode530. Minimum Absolute Difference in BST
- LeetCode-530. Minimum Absolute Difference in BST (Java)
- [leetcode]: 530. Minimum Absolute Difference in BST
- leetcode 530. Minimum Absolute Difference in BST(easy)
- [LeetCode] 530. Minimum Absolute Difference in BST
- leetcode 530. Minimum Absolute Difference in BST
- 530. Minimum Absolute Difference in BST二叉搜索树
- LeetCode 530. Minimum Absolute Difference in BST