当前位置: 首页 > news >正文

LeetCode669. Trim a Binary Search Tree

文章目录

    • 一、题目
    • 二、题解

一、题目

Given the root of a binary search tree and the lowest and highest boundaries as low and high, trim the tree so that all its elements lies in [low, high]. Trimming the tree should not change the relative structure of the elements that will remain in the tree (i.e., any node’s descendant should remain a descendant). It can be proven that there is a unique answer.

Return the root of the trimmed binary search tree. Note that the root may change depending on the given bounds.

Example 1:

Input: root = [1,0,2], low = 1, high = 2
Output: [1,null,2]
Example 2:

Input: root = [3,0,4,null,2,null,null,1], low = 1, high = 3
Output: [3,2,null,1]

Constraints:

The number of nodes in the tree is in the range [1, 104].
0 <= Node.val <= 104
The value of each node in the tree is unique.
root is guaranteed to be a valid binary search tree.
0 <= low <= high <= 104

二、题解

/*** Definition for a binary tree node.* struct TreeNode {*     int val;*     TreeNode *left;*     TreeNode *right;*     TreeNode() : val(0), left(nullptr), right(nullptr) {}*     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}*     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}* };*/
class Solution {
public:TreeNode* trimBST(TreeNode* root, int low, int high) {if(!root) return nullptr;if(root->val < low) return trimBST(root->right,low,high);else 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;}
};
http://www.lryc.cn/news/236897.html

相关文章:

  • YOLOv8优化策略:轻量级Backbone改进 | VanillaNet极简神经网络模型 | 华为诺亚2023
  • 【数据结构(二)】稀疏 sparsearray 数组(1)
  • MySQL的执行器是怎么工作的
  • 【目标测距】雷达投影测距
  • uniapp、小程序canvas相关
  • [工业自动化-23]:西门子S7-15xxx编程 - 软件编程 - 西门子PLC人机界面交互HMI功能概述、硬件环境准备、软件环境准备
  • 在Ubuntu系统中安装VNC并结合内网穿透实现公网远程访问
  • java基础练习缺少项目?看这篇文章就够了(上)!
  • 鸿蒙为什么使用typescript 作为开发语言 而不是 flutter 或者 kotlin
  • Flutter NestedScrollView 、SliverAppBar全解析,悬浮菜单的应用
  • Mongodb 副本集名称重命名
  • C#WPF属性触发器实例
  • Kotlin 核心语法,为什么选择Kotlin ?
  • SpringCloud微服务:Nacos的集群、负载均衡、环境隔离
  • Selenium+Python做web端自动化测试框架实战
  • Linux:安装MySQL服务(非docker方式)
  • C++实现有理数类 四则运算和输入输出
  • 小鸟飞呀飞
  • Unity 场景烘培 ——unity Post-Processing后处理1(四)
  • Burpsuite抓HTTPS证书导入问题
  • python保存文件到zip压缩包中
  • java发送媒体类型为multipart/form-data的请求
  • 自定义类使用ArrayList中的remove
  • 前端面试考核点【更持续新中】
  • linux-docker安装
  • 如何用html css js 画出曲线 或者斜线;
  • 【错误记录】Uncaught TypeError: m.nodeName.toLowerCase is not a function
  • 王颖奇:ONES.ai 上线,以及我的一些思考
  • 将AI技术与VR元宇宙相结合的整体解决方案
  • IPKISS Tutorials 3------绘制矩形版图