【LeetCode】538. Convert BST to Greater Tree 解题报告(Python)
2024-10-19 08:56:58
作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/
题目地址:https://leetcode.com/problems/convert-bst-to-greater-tree/description/
题目描述
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
题目大意
把BST的每个节点的值重新设置为所有比它值大的节点的值的和。
解题方法
递归
这个题要把每个节点变为比该节点值大(包含)的所有节点之和。
这个题的动机是我们应该先修改数值比较大的节点,然后修改数值比较小的节点。这样做,才能保证,我们只需要一次遍历,就把每个节点的值修改成了比它值更大的所有节点的和。
BST的右子树都比该节点大,所以修改次序是右–>中–>左。用一个变量储存遍历过程中所有有节点之和就得到了所有的比当前把该节点的值更大的和,然后修改为该变量的值即可。
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def convertBST(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
self.sum = 0
def afterOrder(cur):
if not cur: return
afterOrder(cur.right)
self.sum += cur.val
cur.val = self.sum
afterOrder(cur.left)
afterOrder(root)
return root
日期
2018 年 1 月 22 日
2018 年 11 月 13 日 —— 时间有点快
最新文章
- android studio sdk 不能更新
- ****CI框架源码阅读笔记7 配置管理组件 Config.php
- LeetCode ---Anagrams() 详解
- POJ 2349 Arctic Network (最小生成树)
- zookeeper的配置项
- SGU 438 The Glorious Karlutka River =) ★(动态+分层网络流)
- 编译驱动时出现";Cannot open file trace.h";错误
- 你的Jsp页面有黄×么,有黄色问号么?Multiple annotations found at this line: - Invalid location of tag (form). - No
- Python之路第三天,基础(3)-set,函数,内置函数,文件,三元运算,lambda
- 【20171104中】chrome自动刷新网页
- 20164305 徐广皓 Exp5 MSF基础应用
- Spring-day03
- bootstrap实现列的拖动
- js2wordcloud 词云包的使用
- 剑指offer错题记录
- HDMI传输原理:TMDS
- SQL Server2005/2008 作业执行失败的解决办法
- Promise 模式解析:Promise模式与异步及声明式编程
- spark优化之数据结构(减少内存)
- jquery.form 和MVC4做无刷新上传DEMO