博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] 538. Convert BST to Greater Tree
阅读量:4677 次
发布时间:2019-06-09

本文共 963 字,大约阅读时间需要 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 题意:给定一个二叉搜索树,把它转换成为累加树,使得每个节点的值是原来的节点值加上所有大于它的节点值之和。 做树的题一定要利用条件,就是特别的给了一个什么样的树,这个树有什么特性 二叉搜索树的特点是 右>根>左,也就是说中序有序,我们把中序倒过来就正好是从大到小的 什么意思呢,就是当你遍历到某个节点的时候,比它大的都已经遍历完了,我们只需维护一个max就行
class Solution {    private int max = 0;    private void convert(TreeNode root) {        if (root == null)            return;        convert(root.right);        root.val += max;        max = root.val;        convert(root.left);    }    public TreeNode convertBST(TreeNode root) {        convert(root);        return root;    }}

 

 

转载于:https://www.cnblogs.com/Moriarty-cx/p/9784395.html

你可能感兴趣的文章
《20171201-构建之法:现代软件工程-阅读笔记》
查看>>
ajaxpro简单调用
查看>>
爬网页数据
查看>>
eclipse内存溢出 参数配置
查看>>
页面元素定位 XPath 简介
查看>>
贪心/poj 1017 Packets
查看>>
[转]loadrunner:系统的平均并发用户数和并发数峰值如何估算
查看>>
Linux下Tomcat重新启动
查看>>
时间复杂度
查看>>
HTML Table to Json
查看>>
Theano 学习笔记(一)
查看>>
1.7 节点进行排序显示
查看>>
web最佳实践
查看>>
spring 集成shiro 之 自定义过滤器
查看>>
验证密码不允许有连续三位重复的正则表达式
查看>>
python 中对list去重
查看>>
Mono Libgdiplus库
查看>>
js模糊查询案例
查看>>
c语言基础知识要点
查看>>
Android模拟器无法上网访问网络失败解决办法
查看>>