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

力扣 669. 修剪二叉搜索树

题目来源:https://leetcode.cn/problems/trim-a-binary-search-tree/description/

 

 C++题解1:递归法。当前节点为空时返回空,不为空时对其值进行分类讨论。以low为例,当前节点值等于low时,意味着其左子树都要丢弃,可指向空;大于low时,说明其左子树也可能满足条件,因此对其左子树进一步递归;小于low时,说明当前节点及其左子树都不满足条件,将当前节点更新为其右子节点。

class Solution {
public:TreeNode* trimBST(TreeNode* root, int low, int high) {if(!root) return nullptr;if(root->val == low) root->left = nullptr; else if(root->val > low) {root->left = trimBST(root->left, low, high);}else {root = root->right;return trimBST(root, low, high);}if(root->val == high) root->right = nullptr;else if(root->val < high) {root->right = trimBST(root->right, low, high);}else {root = root->left;return trimBST(root, low, high);}return root;}
};

C++题解2:递归法。大致思路同上,较为精简,来源代码随想录。

class Solution {
public:TreeNode* trimBST(TreeNode* root, int low, int high) {if (root == nullptr) return nullptr;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;}
};

C++题解3:迭代法。见注释,来源代码随想录。

class Solution {
public:TreeNode* trimBST(TreeNode* root, int L, int R) {if (!root) return nullptr;// 处理头结点,让root移动到[L, R] 范围内,注意是左闭右闭while (root != nullptr && (root->val < L || root->val > R)) {if (root->val < L) root = root->right; // 小于L往右走else root = root->left; // 大于R往左走}TreeNode *cur = root;// 此时root已经在[L, R] 范围内,处理左孩子元素小于L的情况while (cur != nullptr) {while (cur->left && cur->left->val < L) {cur->left = cur->left->right;}cur = cur->left;}cur = root;// 此时root已经在[L, R] 范围内,处理右孩子大于R的情况while (cur != nullptr) {while (cur->right && cur->right->val > R) {cur->right = cur->right->left;}cur = cur->right;}return root;}
};

http://www.lryc.cn/news/94282.html

相关文章:

  • ChatGPT在多轮对话中的表现如何?
  • C++ 虚函数 (virtual function) 介绍
  • 写给小白的ChatGPT和AI原理
  • 多元回归预测 | Matlab基于麻雀算法(SSA)优化混合核极限学习机HKELM回归预测, SSA-HKELM数据回归预测,多变量输入模型
  • High Performance Visual Tracking with Siamese Region Proposal Network(SiamRPN)
  • 【Vue3 生态】VueRouter 路由核心知识点
  • SpringCloud-Nacos配置管理
  • 物流智能分拣管理
  • Qt编写视频监控系统79-四种界面导航栏的设计
  • 界面开发框架Qt新手入门教程:如何使用Calendar组件创建日历(二)
  • charles unknown 问题和手机代理设置(iOS手机)
  • 【备战秋招】每日一题:2023.03.26-阿里OD机试(第三题)-数组之和最小值
  • 网站的SEO优化:提升搜索引擎可见性的关键步骤
  • Spring Boot 中的服务注册是什么,原理,如何使用
  • spring.factories文件在Spring工程中的说明
  • 常见的自动化测试架构有哪些?
  • Revit中用自适应创建简单的瓦片族和切换构件的材质?
  • Spring Boot实战:拦截器和监听器的应用指南
  • 为什么要搭建数据仓库
  • Sql Server 获取连续日期时间
  • MIT 6.830数据库系统 -- lab two
  • React基础知识点(一)
  • 机器学习-进化算法
  • leetcode 637. 二叉树的层平均值
  • 7-数组创建函数还有哪些?【视频版】
  • webrtc源码阅读之P2P流程分析
  • vscode 快速修复(quick fix) 快捷键(Ctrl + .)被占用问题解决方法
  • 阿里云——扩展Linux系统盘
  • TypeScript ~ 掌握基本类型 ②
  • 【Zookeeper】win安装随笔