day57(1.8)——leetcode面试经典150

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

530. 二叉搜索树的最小绝对值

题目:

题解:

一开始用的笨办法:

java 复制代码
/**
 * 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 {
    public int getMinimumDifference(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        List<Integer> list = new ArrayList<>();
        while(queue.size()>0) {
            int size = queue.size();
            for(int i=0;i<size;i++) {
                TreeNode node = queue.poll();
                list.add(node.val);
                if(node.left != null) {
                    queue.offer(node.left);
                }
                if(node.right != null) {
                    queue.offer(node.right);
                }
            }
        }
        list.sort(null);
        int minn = Integer.MAX_VALUE;
        for(int i=1;i<list.size();i++) {
            minn = Math.min(minn, list.get(i)-list.get(i-1));
        }
        return minn;
    }
}

妙哉,用中序遍历

java 复制代码
/**
 * 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 {
    public int minn = Integer.MAX_VALUE;
    public int pre = Integer.MIN_VALUE/2;

    public int getMinimumDifference(TreeNode root) {
        dfs(root);
        return minn;
    }

    public void dfs(TreeNode root) {
        if(root == null) {
            return ;
        }
        dfs(root.left);
        minn = Math.min(minn, root.val-pre);
        pre = root.val;
        dfs(root.right);
    }
}
相关推荐
超级码力6666 小时前
【Latex文件架构】Latex文件架构模板
算法·数学建模·信息可视化
穿条秋裤到处跑6 小时前
每日一道leetcode(2026.04.29):二维网格图中探测环
算法·leetcode·职场和发展
Merlos_wind6 小时前
HashMap详解
算法·哈希算法·散列表
汉克老师7 小时前
GESP2025年3月认证C++五级( 第三部分编程题(1、平均分配))
c++·算法·贪心算法·排序·gesp5级·gesp五级
Yzzz-F9 小时前
Problem - 2205D - Codeforces
算法
智者知已应修善业10 小时前
【51单片机2个按键控制流水灯运行与暂停】2023-9-6
c++·经验分享·笔记·算法·51单片机
Halo_tjn10 小时前
Java Set集合相关知识点
java·开发语言·算法
许彰午10 小时前
我手写了一个 Java 内存数据库(二):B+ 树的插入与分裂
java·开发语言·面试
生成论实验室11 小时前
《事件关系阴阳博弈动力学:识势应势之道》第四篇:降U动力学——认知确定度的自驱演化
人工智能·科技·神经网络·算法·架构
AI科技星11 小时前
全域数学·72分册:场计算机卷【乖乖数学】
算法·机器学习·数学建模·数据挖掘·量子计算