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.
Inorder Traverse
Time Complexity
O(logn)
Space Complexity
O(1)
思路
Because it is a BST, so the smallest absolute number is near each other by using inorder traverse, keep one global minDiff by traversing the whole tree.
代码
private int minDiff = Integer.MAX_VALUE;
private TreeNode pre = null;
public int getMinimumDifference(TreeNode root) {
inorder(root);
return minDiff;
}
private void inorder(TreeNode root){
if(root == null) return;
inorder(root.left);
if(pre != null) minDiff = Math.min(Math.abs(root.val - pre.val), minDiff);
pre = root;
inorder(root.right);
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。