力扣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);
    }
}
相关推荐
serve the people1 分钟前
springboot 单独新建一个文件实时写数据,当文件大于100M时按照日期时间做文件名进行归档
java·spring boot·后端
qmx_071 小时前
HTB-Jerry(tomcat war文件、msfvenom)
java·web安全·网络安全·tomcat
X同学的开始1 小时前
数据结构之二叉树遍历
数据结构
为风而战1 小时前
IIS+Ngnix+Tomcat 部署网站 用IIS实现反向代理
java·tomcat
limingade2 小时前
手机实时提取SIM卡打电话的信令和声音-新的篇章(一、可行的方案探讨)
物联网·算法·智能手机·数据分析·信息与通信
技术无疆3 小时前
快速开发与维护:探索 AndroidAnnotations
android·java·android studio·android-studio·androidx·代码注入
AIAdvocate4 小时前
Pandas_数据结构详解
数据结构·python·pandas
jiao000014 小时前
数据结构——队列
c语言·数据结构·算法
kaneki_lh5 小时前
数据结构 - 栈
数据结构
铁匠匠匠5 小时前
从零开始学数据结构系列之第六章《排序简介》
c语言·数据结构·经验分享·笔记·学习·开源·课程设计