问题:
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).
解决:
① 通过中序遍历可以得到一个有序数列,然后将当前节点值和之前节点值求绝对差并更新结果min。需要注意的就是在处理第一个节点值时,由于其没有前节点,所以不能求绝对差。这里我们用变量pre来表示前节点值,这里由于题目中说明了所以节点值不为负数,所以我们给pre初始化-1,这样我们就知道pre是否存在。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution { //17ms
int minVal = Integer.MAX_VALUE;
int pre = -1;
public int getMinimumDifference(TreeNode root) {
inorder(root);
return minVal;
}
public void inorder(TreeNode root){
if(root == null) return;
inorder(root.left);
if(pre != -1) minVal = Math.min(minVal,root.val - pre);
pre = root.val;
inorder(root.right);
}
}
② 进化版
public class Solution { //14ms
int min = Integer.MAX_VALUE;//因为使用了递归方法,所以必须声明为全局变量,否则结果错误
Integer prev = null;
public int getMinimumDifference(TreeNode root) {
if (root == null) return min;
getMinimumDifference(root.left);
if (prev != null) {
min = Math.min(min, root.val - prev);
}
prev = root.val;
getMinimumDifference(root.right);
return min;
}
}
③ 使用非递归方法实现。
public class Solution { //19ms
public int getMinimumDifference(TreeNode root) {
int minVal = Integer.MAX_VALUE;
int pre = -1;
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
while(cur != null || ! stack.isEmpty()){
while(cur != null){
stack.push(cur);
cur = cur.left;
}
cur = stack.pop();
if(pre != -1) minVal = Math.min(minVal,cur.val - pre);
pre = cur.val;
cur = cur.right;
}
return minVal;
}
}