力扣530.二叉搜索树的最小绝对差

简介: 力扣530.二叉搜索树的最小绝对差
https://leetcode.cn/problems/minimum-absolute-difference-in-bst/submissions/
思路:二叉搜索树求最小差的绝对值,二叉搜索树是有序的,因此采用中序递归即可
步骤:关键要定义pre节点,构造函数,传入节点;
    给出树为空的边界,之后进入递归;
    构造递归函数,传入根节点
class Solution {
    TreeNode pre;
    int result = Integer.MAX_VALUE;//表示int数据类型的最大取值数:2 147 483 647
    public int getMinimumDifference(TreeNode root) {
        if (root == null) {
            return 0;
        }
        traversal(root);
        return result;
    }
    public void traversal(TreeNode root) {
        if (root == null) {
            return; //此处为什么二次判断???用来判断递归到左叶子节点处
        }
        traversal(root.left);
        if (pre != null) {
            result = Math.min(result, root.val - pre.val);
        }
        pre = root;
        traversal(root.right);
    }
}


相关文章
|
机器学习/深度学习 存储 算法
LeetCode 题目 95:从递归到动态规划实现 不同的二叉搜索树 II
LeetCode 题目 95:从递归到动态规划实现 不同的二叉搜索树 II
【LeetCode 45】701.二叉搜索树中的插入操作
【LeetCode 45】701.二叉搜索树中的插入操作
72 1
【LeetCode 44】235.二叉搜索树的最近公共祖先
【LeetCode 44】235.二叉搜索树的最近公共祖先
89 1
|
Python
【Leetcode刷题Python】450. 删除二叉搜索树中的节点
LeetCode上538号问题"把二叉搜索树转换为累加树"的Python实现,使用反向中序遍历并记录节点值之和来更新每个节点的新值。
119 4
【Leetcode刷题Python】450. 删除二叉搜索树中的节点
|
Python
【Leetcode刷题Python】96. 不同的二叉搜索树
LeetCode 96题 "不同的二叉搜索树" 的Python解决方案,使用动态规划算法计算由1至n互不相同节点值组成的二叉搜索树的种数。
98 3
【Leetcode刷题Python】96. 不同的二叉搜索树
【LeetCode 48】108.将有序数组转换为二叉搜索树
【LeetCode 48】108.将有序数组转换为二叉搜索树
115 0
【LeetCode 47】669.修剪二叉搜索树
【LeetCode 47】669.修剪二叉搜索树
68 0
【LeetCode 46】450.删除二叉搜索树的节点
【LeetCode 46】450.删除二叉搜索树的节点
129 0
【LeetCode 42】501.二叉搜索树中的众数
【LeetCode 42】501.二叉搜索树中的众数
80 0
【LeetCode 41】530.二叉搜索树的最小绝对差
【LeetCode 41】530.二叉搜索树的最小绝对差
82 0