给你一个二叉搜索树的根节点 root ,返回 树中任意两不同节点值之间的最小差值 。

    差值是一个正数,其数值等于两值之差的绝对值。

    示例 1:
    image.png

    输入:root = [4,2,6,1,3]
    输出:1
    示例 2:

    输入:root = [1,0,48,null,null,12,49]
    输出:1

    提示:

    树中节点的数目范围是 [2, 104]
    0 <= Node.val <= 105


    1. /**
    2. * Definition for a binary tree node.
    3. * public class TreeNode {
    4. * int val;
    5. * TreeNode left;
    6. * TreeNode right;
    7. * TreeNode() {}
    8. * TreeNode(int val) { this.val = val; }
    9. * TreeNode(int val, TreeNode left, TreeNode right) {
    10. * this.val = val;
    11. * this.left = left;
    12. * this.right = right;
    13. * }
    14. * }
    15. */
    16. class Solution {
    17. int res = 0x3f3f3f3f;
    18. int pre = 0x3f3f3f3f;
    19. //中序遍历,因为是递增的,所以相邻节点肯定是相差最小的
    20. public int getMinimumDifference(TreeNode root) {
    21. dfs(root);
    22. return res;
    23. }
    24. private void dfs(TreeNode root) {
    25. if (root == null) return;
    26. dfs(root.left);
    27. res = Math.min(res, Math.abs(pre - root.val));
    28. pre = root.val;
    29. dfs(root.right);
    30. }
    31. }