作者: 负雪明烛
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 日 —— 时间有点快

最新文章

  1. android studio sdk 不能更新
  2. ****CI框架源码阅读笔记7 配置管理组件 Config.php
  3. LeetCode ---Anagrams() 详解
  4. POJ 2349 Arctic Network (最小生成树)
  5. zookeeper的配置项
  6. SGU 438 The Glorious Karlutka River =) ★(动态+分层网络流)
  7. 编译驱动时出现"Cannot open file trace.h"错误
  8. 你的Jsp页面有黄×么,有黄色问号么?Multiple annotations found at this line: - Invalid location of tag (form). - No
  9. Python之路第三天,基础(3)-set,函数,内置函数,文件,三元运算,lambda
  10. 【20171104中】chrome自动刷新网页
  11. 20164305 徐广皓 Exp5 MSF基础应用
  12. Spring-day03
  13. bootstrap实现列的拖动
  14. js2wordcloud 词云包的使用
  15. 剑指offer错题记录
  16. HDMI传输原理:TMDS
  17. SQL Server2005/2008 作业执行失败的解决办法
  18. Promise 模式解析:Promise模式与异步及声明式编程
  19. spark优化之数据结构(减少内存)
  20. jquery.form 和MVC4做无刷新上传DEMO

热门文章

  1. Scrapy爬虫框架的安装和使用
  2. 工作学习2-gcc升级引发的崩溃
  3. Vue3 中有哪些值得深究的知识点?
  4. 学习java第十九天
  5. accomplish, accord
  6. day17 常用模块的应用
  7. echo -e "\033[字背景颜色;字体颜色m字符串\033[0m
  8. OC-引用计数器,内存管理,野指针
  9. lambda表达式快速创建
  10. js 长按鼠标左键实现溢出内容左右滚动滚动