Problem
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).
Solution
public class Solution {
/**
* @param root: the root
* @return: the minimum absolute difference between values of any two nodes
*/
private final int diff = Integer.MAX_VALUE;
public int getMinimumDifference(TreeNode root) {
// take root for example, the min diff should be the diff of
// 1. `root` and `root.left's rightmost child`
// 2. `root` and `root.right's leftmost child`
if (root == null) return diff;
int res = Integer.MAX_VALUE, leftmost = -1, rightmost = -1;
if (root.left != null) {
rightmost = getRightMost(root.left);
}
if (root.right != null) {
leftmost = getLeftMost(root.right);
}
if (leftmost != -1) {
res = Math.min(res, Math.abs(root.val - leftmost));
}
if (rightmost != -1) {
res = Math.min(res, Math.abs(root.val - rightmost));
}
res = Math.min(res, getMinimumDifference(root.left));
res = Math.min(res, getMinimumDifference(root.right));
return res;
}
public int getLeftMost(TreeNode node) {
while (node.left != null) node = node.left;
return node.val;
}
public int getRightMost(TreeNode node) {
while (node.right != null) node = node.right;
return node.val;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。