解法一:中序遍历

对二叉搜索树进行中序遍历可以得到升序序列,最小绝对差可以从相邻两个结点的差中取得。

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. class Solution {
  11. private int minDelta;
  12. private TreeNode last;
  13. public int getMinimumDifference(TreeNode root) {
  14. minDelta = Integer.MAX_VALUE;
  15. last = null;
  16. inOrder(root);
  17. return minDelta;
  18. }
  19. private void inOrder(TreeNode root) {
  20. if (root == null) {
  21. return;
  22. }
  23. inOrder(root.left);
  24. if (last != null) {
  25. minDelta = Math.min(minDelta, root.val - last.val);
  26. }
  27. last = root;
  28. inOrder(root.right);
  29. }
  30. }