给你一个二叉搜索树的根节点 root ,返回 树中任意两不同节点值之间的最小差值 。
差值是一个正数,其数值等于两值之差的绝对值。
示例 1:
输入:root = [4,2,6,1,3]
输出:1
示例 2:
输入:root = [1,0,48,null,null,12,49]
输出:1
提示:
树中节点的数目范围是 [2, 104]
0 <= Node.val <= 105
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int res = 0x3f3f3f3f;
int pre = 0x3f3f3f3f;
//中序遍历,因为是递增的,所以相邻节点肯定是相差最小的
public int getMinimumDifference(TreeNode root) {
dfs(root);
return res;
}
private void dfs(TreeNode root) {
if (root == null) return;
dfs(root.left);
res = Math.min(res, Math.abs(pre - root.val));
pre = root.val;
dfs(root.right);
}
}