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