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 13 Output: The root of a Greater Tree like this:
18
/ \
20 13
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int sum = 0;
public TreeNode convertBST(TreeNode root) {
helper(root);
return root;
} public void helper (TreeNode root){
if(root == null){
return;
}
helper(root.right);
sum = sum + root.val;
root.val = sum;
helper(root.left); }
}

反着中序遍历, 就会从大到小排序,注意要用一个 global 变量保存状态。

最新文章

  1. 台式机装原版Win2008R2
  2. 关于SSH的一些tricks
  3. php大力力 [049节] php函数implode()
  4. Git 在团队中的最佳实践--如何正确使用Git Flow[转]
  5. 虚拟化平台cloudstack(6)——使用maven:jetty调试
  6. UIWebView的应用和其中的JS与OC间传值
  7. Google翻译请求(难点是tk参数)
  8. Array.prototype.indexOf
  9. C#中将结构类型数据存储到二进制文件中方法
  10. 《JS高程》数据类型学习笔记
  11. Linux 上的基础网络设备详解
  12. Java NIO API详解
  13. 【性能测试】【Jmeter】学习(1)
  14. Android自定义日历,可以点击、标注日期、节气、旧历等
  15. Unix命令行学习
  16. 局部敏感哈希(Locality-Sensitive Hashing, LSH)方法介绍
  17. 1.3if判断语句+while和for循环语句+购物车作业
  18. [CSS] Scale on Hover with Transition
  19. SQL的六种约束
  20. [Python设计模式] 第20章 挨个买票——迭代器模式

热门文章

  1. React中禁止chrome填充密码表单
  2. 外部点击链接,登陆后,直接跳转到该链接(过滤器 + Cookie实现)
  3. Java面向对象的三大特性之一 多态
  4. sqlalchemy 简介
  5. [leetcode整理]
  6. Java输入输出小结
  7. ssm使用双数据源
  8. 用MFC库函数AfxBeginThread()来创建线程
  9. 多进程于多线程的区别,cpu密集型适合用什么
  10. Linux并发执行很简单,这么干就对了