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);
    }
}
相关推荐
啊森要自信9 小时前
CANN ops-cv:AI 硬件端视觉算法推理训练的算子性能调优与实战应用详解
人工智能·算法·cann
仟濹9 小时前
算法打卡day2 (2026-02-07 周五) | 算法: DFS | 3_卡码网99_计数孤岛_DFS
算法·深度优先
驭渊的小故事10 小时前
简单模板笔记
数据结构·笔记·算法
YuTaoShao10 小时前
【LeetCode 每日一题】1653. 使字符串平衡的最少删除次数——(解法一)前后缀分解
算法·leetcode·职场和发展
VT.馒头10 小时前
【力扣】2727. 判断对象是否为空
javascript·数据结构·算法·leetcode·职场和发展
goodluckyaa10 小时前
LCR 006. 两数之和 II - 输入有序数组
算法
孤狼warrior10 小时前
YOLO目标检测 一千字解析yolo最初的摸样 模型下载,数据集构建及模型训练代码
人工智能·python·深度学习·算法·yolo·目标检测·目标跟踪
Σίσυφος190010 小时前
PCL法向量估计 之 RANSAC 平面估计法向量
算法·机器学习·平面
xhbaitxl11 小时前
算法学习day39-动态规划
学习·算法·动态规划
I_LPL11 小时前
day23 代码随想录算法训练营 回溯专题2
算法·hot100·回溯算法·求职面试