LeetCode 530.二叉搜索树的最小绝对差 详细解读

题目:简单题
给定一个二叉树,返回树中任意两节点值的最小差值。差值是一个正数。

思路:太菜了,题都没看懂。因为二叉搜索树中序遍历是一个有序的递增的数组,最小差值肯定是相邻元素之间的差值。

代码

class Solution {
    
    
    int pre;
    int ans;

    public int getMinimumDifference(TreeNode root) {
    
    
        ans = Integer.MAX_VALUE;
        pre = -1;
        dfs(root);
        return ans;
    }

    public void dfs(TreeNode root) {
    
    
        if (root == null) {
    
    
            return;
        }
        dfs(root.left);
        if (pre == -1) {
    
    
            pre = root.val;
        } else {
    
    
            ans = Math.min(ans, root.val - pre);
            pre = root.val;
        }
        dfs(root.right);
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43744992/article/details/121762198
今日推荐