解法一:中序遍历
对二叉搜索树进行中序遍历可以得到升序序列,最小绝对差可以从相邻两个结点的差中取得。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private int minDelta;
private TreeNode last;
public int getMinimumDifference(TreeNode root) {
minDelta = Integer.MAX_VALUE;
last = null;
inOrder(root);
return minDelta;
}
private void inOrder(TreeNode root) {
if (root == null) {
return;
}
inOrder(root.left);
if (last != null) {
minDelta = Math.min(minDelta, root.val - last.val);
}
last = root;
inOrder(root.right);
}
}