LeetCode 783二叉搜索树节点的最小距离(Java)

LeetCode 783二叉搜索树节点的最小距离(Java)_第1张图片

class Solution {
    Integer pre;
    int min = Integer.MAX_VALUE;

    public int minDiffInBST(TreeNode root) {
        // 中序递归
        int res = dfs(root);
        return res;
    }

    private int dfs(TreeNode root) {
        // 判断特例
        if (root == null)
            return 0;
        // 遍历左子树
        dfs(root.left);
        // 中间
        if (pre != null) {
            min = Math.min(min, root.val - pre);
        }
        pre = root.val;
        // 右边
        dfs(root.right);
        return min;
    }
}

你可能感兴趣的:(LeetCode刷题系列)