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