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

LeetCode538. Convert BST to Greater Tree

文章目录

    • 一、题目
    • 二、题解

一、题目

Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.

As a reminder, a binary search tree is a tree that satisfies these constraints:

The left subtree of a node contains only nodes with keys less than the node’s key.
The right subtree of a node contains only nodes with keys greater than the node’s key.
Both the left and right subtrees must also be binary search trees.

Example 1:

Input: root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]
Output: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]
Example 2:

Input: root = [0,null,1]
Output: [1,null,1]

Constraints:

The number of nodes in the tree is in the range [0, 104].
-104 <= Node.val <= 104
All the values in the tree are unique.
root is guaranteed to be a valid binary search tree.

二、题解

/*** 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* pre = nullptr;//双指针,按右中左遍历TreeNode* convertBST(TreeNode* root) {if(!root) return nullptr;convertBST(root->right);if(pre) root->val += pre->val;pre = root;convertBST(root->left);return root;}
};
http://www.lryc.cn/news/237585.html

相关文章:

  • iPaaS和RPA,企业自动化应该如何选择?
  • AI实践与学习1_Milvus向量数据库实践与原理分析
  • 3Dexcite deltgen 2022x 新功能
  • 代码随想录算法训练营第六十天 | LeetCode 84. 柱状图中最大的矩形
  • 【2023云栖】陈守元:阿里云开源大数据产品年度发布
  • Element UI 禁用数字输入框组件添加鼠标滚动事件
  • 担忧CentOS停服?KeyarchOS系统来支撑
  • 聚观早报 |联想集团Q2财季业绩;小鹏汽车Q3营收
  • SAP ABAP权限控制中常用TCODE
  • 云计算赛项容器云2023搭建
  • 11.1 文件拷贝移动与删除
  • redhat下使用CentOS yum源,并安装docker
  • 基于单片机体温脉搏检测控制系统及源程序
  • MyBatis-Plus逻辑删@TableLogic
  • 本地私域线上线下 线上和线下的小程序
  • 【前端学java】java中的Object类(8)
  • TensorFlow实战教程(二十六)-什么是生成对抗网络GAN?基础原理和代码普及
  • IDEA版SSM入门到实战(Maven+MyBatis+Spring+SpringMVC) -Maven依赖管理,版本号管理,继承和聚合
  • OpenVPN Connect使用连接公网VPN服务器实现内网穿透
  • Redis(集合Set和有序集合SortedSet)
  • 黔院长 | 《黄帝内经》——奇病论!
  • 手撕单链表(C语言)
  • 60 权限提升-MYMSORA等SQL数据库提权
  • 【C++上层应用】2. 预处理器
  • ISP--Black Level Correction(黑电平矫正)
  • python项目源码基于django的宿舍管理系统dormitory+mysql数据库文件
  • Java和 JS 的10大不同之处,你清楚吗?
  • vue动态配置路由
  • 科技云报道:全球勒索攻击创历史新高,如何建立网络安全的防线?
  • 通过bat命令启动jar后缀软件