661.Convert BST to Greater Tree
来源:互联网 发布:淘宝卖家为什么改价格 编辑:程序博客网 时间:2024/05/20 05:58
题目:
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.
样例
Given a binary search Tree `{5,2,3}`:
5 / \ 2 13
Return the root of new tree
18 / \ 20 13
代码:
class Solution {public: /** * @param root the root of binary tree * @return the new root */ // Write your code here int sum=0; void travel(TreeNode* root) { if(root==NULL) return ; if (root->right) { travel(root->right); } sum+=(root->val); root->val=sum; if (root->left) { travel(root->left); } } TreeNode* convertBST(TreeNode* root) { travel(root); return root; } };思想:从右往左递归累计加值,然后复制给当前节点。
0 0
- 661.Convert BST to Greater Tree
- Convert BST to Greater Tree
- Convert BST to Greater Tree
- Convert BST to Greater Tree
- Convert BST to Greater Tree
- Convert BST to Greater Tree
- Convert BST to Greater Tree
- Convert BST to Greater Tree
- Convert BST to Greater Tree
- Convert BST to Greater Tree
- Convert BST to Greater Tree
- Convert BST to Greater Tree
- Convert BST to Greater Tree
- Convert BST to Greater Tree
- Convert BST to Greater Tree
- convert bst to greater tree
- Convert BST to Greater Tree
- Convert BST to Greater Tree
- 【学习笔记】Jesse Schell's six lessons for making VR games
- MySQL
- 数据结构 — 二叉树的线索化
- Ubuntu Fluxbox GUI with x11vnc and Xvfb
- iOS 退出登录
- 661.Convert BST to Greater Tree
- Celery定时任务
- excel字段过多,导入数据库 存在截断问题的解决方法
- HTML5学习笔记 —— JavaScript开发入门
- lua脚本语言学习
- 前端框架Vue(10)——vuex 状态管理
- 陶陶摘苹果
- weasis调节窗位相关代码分析
- Zstack之RSSI信号值获取以及显示