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

代码随想录day27

669.

/*
 * @lc app=leetcode.cn id=669 lang=cpp
 *
 * [669] 修剪二叉搜索树
 */

// @lc code=start
/**
 * 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 == nullptr ) return nullptr;
        if (root->val < low) {
            TreeNode* right = trimBST(root->right, low, high); 
            return right;
        }
        if (root->val > high) {
            TreeNode* left = trimBST(root->left, low, high); 
            return left;
        }
        root->left = trimBST(root->left, low, high); 
        root->right = trimBST(root->right, low, high); 
        return root; 
    }
};
// @lc code=end

108

class Solution {
private:
    TreeNode* traversal(vector<int>& nums, int left, int right) {
        if (left > right) return nullptr;
        int mid = left + ((right - left) / 2);
        TreeNode* root = new TreeNode(nums[mid]);
        root->left = traversal(nums, left, mid - 1);
        root->right = traversal(nums, mid + 1, right);
        return root;
    }
public:
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        TreeNode* root = traversal(nums, 0, nums.size() - 1);
        return root;
    }
};

 538

class Solution {
private:
    int pre = 0; 
    void traversal(TreeNode* cur) { 
        if (cur == NULL) return;
        traversal(cur->right);
        cur->val += pre;
        pre = cur->val;
        traversal(cur->left);
    }
public:
    TreeNode* convertBST(TreeNode* root) {
        pre = 0;
        traversal(root);
        return root;
    }
};


http://www.kler.cn/a/531497.html

相关文章:

  • cpp的STL与java的Collections Framework使用
  • ubuntu解决普通用户无法进入root
  • [HOT 100] 2824. 统计和小于目标的下标对数目
  • Linux——文件系统
  • pytorch实现基于Word2Vec的词嵌入
  • LeetCode 2909. 元素和最小的山形三元组 II
  • FunASR的服务启动_3
  • 02.04 数据类型
  • 前端知识速记--CSS篇:display
  • UE5 蓝图学习计划 - Day 12:存储与加载
  • 使用Pytorch训练一个图像分类器
  • 通信易懂唠唠SOME/IP——SOME/IP消息格式
  • 2024-我的学习成长之路
  • DeepSeek:AI领域的创新先锋
  • 使用mybatisPlus插件生成代码步骤及注意事项
  • 飞行汽车中的无刷外转子电机、人形机器人中的无框力矩电机技术解析与应用
  • 《最小阻力之路》关于愿景的理解和思考
  • NoSQL、时序、搜索……Lindorm 如何一站式搞定多模数据?
  • 《DeepSeek R1:7b 写一个python程序调用摄像头获取视频并显示》
  • SpringMVC全局异常处理+拦截器使用+参数校验
  • C语言的物联网
  • 基于SpringBoot的信息技术知识赛系统的设计与实现(源码+SQL脚本+LW+部署讲解等)
  • bagging框架
  • 什么是 Shell?常见的 Unix Shell有哪些?(中英双语)
  • 【数据结构】_链表经典算法OJ:复杂链表的复制
  • C++基础day1