力扣labuladong——一刷day69

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录

  • 前言
  • [一、力扣669. 修剪二叉搜索树](#一、力扣669. 修剪二叉搜索树)
  • [二、力扣671. 二叉树中第二小的节点](#二、力扣671. 二叉树中第二小的节点)

前言


二叉树的递归分为「遍历」和「分解问题」两种思维模式,这道题需要用到「遍历」的思维模式。

一、力扣669. 修剪二叉搜索树

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 TreeNode trimBST(TreeNode root, int low, int high) {
        if(root == null){
            return null;
        }
        if(root.val < low){
            return trimBST(root.right,low,high);
        }
        if(root.val > high){
            return trimBST(root.left, low, high);
        }
        root.left = trimBST(root.left, low, high);
        root.right = trimBST(root.right, low, high);
        return root;
    }
}

二、力扣671. 二叉树中第二小的节点

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 findSecondMinimumValue(TreeNode root) {
        if(root.left == null && root.right == null){
            return -1;
        }
        int left = root.left.val, right = root.right.val;
        if(root.val == root.left.val){
            left = findSecondMinimumValue(root.left);
        }
        if(root.val == root.right.val){
            right = findSecondMinimumValue(root.right);
        }
        if(left == -1){
            return right;
        }
        if(right == -1){
            return left;
        }
        return Math.min(left,right);
    }
}
相关推荐
SimonKing1 分钟前
DeepSeek 新模型免费白嫖,夯夯夯,赶紧用起来
java·后端·程序员
Young Doro6 分钟前
从平衡表征到最小充分因果表征:端到端神经网络因果效应估计
算法
0+11112 分钟前
算法 --递归
算法·leetcode
打工仔折腾 AI13 分钟前
介入式脑机接口的跨尺度解码与闭环调控:从算法落地到后端工程实践
人工智能·后端·python·深度学习·算法·ai agent 实战
SabrinaW71113 分钟前
基于 C++17 与 RTTR 的注册式对象工厂:配置驱动的动态对象创建
java·前端·数据库
zhangx1234_27 分钟前
javaEE 多线程4
java·开发语言
凤山老林1 小时前
授权模型只会RBAC?深入 ABAC 授权模型,实现权限判断做成策略引擎
大数据·数据库·算法
starzy19901 小时前
KafkaProducer 源码深度剖析:支撑高吞吐的数据结构设计
大数据·数据结构·kafka
中电金信1 小时前
从业务调优到分层缓存:DeepSeek V4 Flash的PPU实践
java·开发语言
snow@li1 小时前
ruoyi-vue-pro/芋道源码:一键改包名/用项目自带的 ‌ProjectReactor‌ 程序/彻底、省事
java