力扣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);
    }
}
相关推荐
葡萄成熟时 !1 天前
JAVA 常用API学习笔记
java·笔记·学习
鹿角片ljp1 天前
LeetCode 46. 全排列|吃透回溯
算法·leetcode·职场和发展
鼎艺创新科技1 天前
不依赖 UE/Unity:我们如何从零搭建一套国产三维 GIS 渲染引擎
人工智能·算法·unity·游戏引擎·三维电子沙盘
Rain的Java大神之路1 天前
介绍一下分布式事务
java·分布式·后端·spring·spring cloud·架构·springcloud
石头猫灯1 天前
WordPress wp2shell 漏洞链完整拆解流程
网络·数据结构·安全·web安全
程序员三藏1 天前
Python+requests实现接口自动化测试
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·接口测试
吴声子夜歌1 天前
Java面试题——基础(一)
java·开发语言
南城以南溫暖如初1471 天前
外卖CPS实战指南:从技术选型到运营落地全流程解析
java·spring boot·mysql·架构·vue
傻啦嘿哟1 天前
英雄联盟皮肤爬虫:爬取全皮肤价格与特效,做比价工具
java·c++·爬虫
.道阻且长.1 天前
11.LeetCode算法习题讲解--滑动窗口--将x减到0的最小操作数
算法·leetcode·职场和发展