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);
    }
}
相关推荐
Hilaku几秒前
为什么很多工作 5 年的前端,身价反而卡住了?🤷‍♂️
前端·javascript·面试
big_rabbit05022 分钟前
JVM堆内存查看命令
java·linux·算法
m0_662577974 分钟前
C++中的RAII技术深入
开发语言·c++·算法
旖-旎4 分钟前
二分查找(点名)(8)
c++·算法·二分查找·力扣
承渊政道7 分钟前
【优选算法】(实战体验滑动窗口的奇妙之旅)
c语言·c++·笔记·学习·算法·leetcode·visual studio
lemonth8 分钟前
图形推理----
人工智能·算法·机器学习
前端炒粉12 分钟前
React 面试高频题
前端·react.js·面试
2401_8914821719 分钟前
C++代码复杂性分析
开发语言·c++·算法
keep intensify21 分钟前
单词搜索-
算法·深度优先
zx_zx_12321 分钟前
定长滑动窗口和不定长滑动窗口
数据结构·算法