力扣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);
    }
}
相关推荐
To_OC1 小时前
LC 207 课程表:刚学图论那会儿,我连这是拓扑排序都没看出来
javascript·算法·leetcode
To_OC1 小时前
LC 208 实现 Trie 前缀树:曾被名字劝退,写完发现是送分题
javascript·算法·leetcode
BadBadBad__AK3 小时前
线段树维护区间 k 次方和
c++·数学·算法·stl
吃饱了得干活7 小时前
Spring Cloud Gateway 微服务网关:路由、断言、过滤器
java·spring cloud
lwx572809 小时前
探秘InnoDB:搞懂它的内存、线程、磁盘与日志刷盘策略
java·后端
Flynt10 小时前
从Spring Boot 4.0升到4.1,我在Maven和gRPC上栽了跟头
java·spring boot·后端
plainGeekDev11 小时前
Activity 间传值 → Navigation 参数
android·java·kotlin
plainGeekDev11 小时前
onActivityResult → ActivityResult API
android·java·kotlin
Sunia11 小时前
《AgentX 专栏》10-生产部署:3台2C4G云服务器把企业级Agent真正跑起来的完整方案
java·架构
ZhengEnCi12 小时前
J7A-高级Java工程师面试三道灵魂拷问-深度广度与工程素养的终极检验
java·后端