Lintcode 661. Convert BST to Greater Tree (Easy) (Python)

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
Given a binary search Tree `{5,2,13}`:

          5
        /   \
       2     13

Return the root of new tree

         18
        /   \
      20     13

Code:

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""

class Solution:
    """
    @param root: the root of binary tree
    @return: the new root
    """

    def convertBST(self, root):
        # write your code here
        self.sum = 0
        def renew(root):
            if root is None:
                return 
            renew(root.right)
            self.sum += root.val
            root.val = self.sum
            renew(root.left)
            return
        renew(root)
        return root

猜你喜欢

转载自blog.csdn.net/weixin_41677877/article/details/80956911
今日推荐