LeetCode C++ 538. Convert BST to Greater Tree【二叉搜索树】简单
发布日期:2021-07-01 02:51:53
浏览次数:2
分类:技术文章
本文共 1009 字,大约阅读时间需要 3 分钟。
Given 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 sum of all keys greater than the original key in BST.
Example:
Input: The root of a Binary Search Tree like this: 5 / \ 2 13Output: The root of a Greater Tree like this: 18 / \ 20 13
题意:给定一个二叉搜索树,把它转换成为累加树,使得每个节点的值是原来的节点值加上所有大于它的节点值之和。
思路:中序遍历的变形。代码如下:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution { public: int sum = 0; TreeNode* convertBST(TreeNode* root) { if (root == nullptr) return root; convertBST(root->right); sum += root->val; root->val = sum; convertBST(root->left); return root; } };
效率如下:
执行用时:60 ms, 在所有 C++ 提交中击败了92.32% 的用户内存消耗:32.4 MB, 在所有 C++ 提交中击败了98.04% 的用户
转载地址:https://memcpy0.blog.csdn.net/article/details/108722930 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
逛到本站,mark一下
[***.202.152.39]2024年04月29日 10时24分07秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
理解和配置Out of memory: Kill process
2019-05-02
MySQL binlog格式解析
2019-05-02
mysql优化——explain详解
2019-05-02
linux 下 pip 安装教程
2019-05-02
运维监控系统之Open-Falcon
2019-05-02
数据库对比:选择MariaDB还是MySQL?
2019-05-02
Mysqlbinlog工具及导出数据并转换编码导入
2019-05-02
使用Percona MySQL 5.7版本遇到的坑
2019-05-02
名词解释:Linux内存管理之RSS和VSZ
2019-05-02
MySQL学习分享--Thread pool实现
2019-05-02
Spring AOP 常用的四种实现方式
2019-05-02
运行时异常与一般异常有何异同
2019-05-02
34. 在排序数组中查找元素的第一个和最后一个位置
2019-05-02
JVM调优总结-基本垃圾回收算法
2019-05-02
线程安全知识
2019-05-02
35. 搜索插入位置
2019-05-02
Collection List Set Map 区别记忆
2019-05-02
"=="和equals方法的区别
2019-05-02
try、catch、finally、return的执行顺序
2019-05-02