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
LeetCode:連結
二叉查找樹(英語:Binary Search Tree),也稱為二叉搜尋樹、有序二叉樹(ordered binary tree)或排序二叉樹(sorted binary tree),是指一棵空樹或者具有下列性質的二叉樹:
- 若任意節點的左子樹不空,則左子樹上所有節點的值均小于它的根節點的值;
- 若任意節點的右子樹不空,則右子樹上所有節點的值均大于它的根節點的值;
- 任意節點的左、右子樹也分别為二叉查找樹;
- 沒有鍵值相等的節點。
二叉搜尋樹的中序周遊結果是元素值由小到大有序的嗎?這題要求把每個結點的值更新為比其大的結點值之和,那倒着來一遍中序周遊就好了。也就是說,由大到小周遊結點,每次累加比目前結點值大的和,指派給目前結點就好了。“右 - 根 - 左”順序周遊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.total = 0
def traverse(root):
if not root:
return None
traverse(root.right)
root.val += self.total
self.total = root.val
traverse(root.left)
traverse(root)
return root