1. 程式人生 > >LeetCode538:Convert BST to Greater Tree

LeetCode538:Convert BST to Greater Tree

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),是指一棵空樹或者具有下列性質的二叉樹

  1. 若任意節點的左子樹不空,則左子樹上所有節點的值均小於它的根節點的值;
  2. 若任意節點的右子樹不空,則右子樹上所有節點的值均大於它的根節點的值;
  3. 任意節點的左、右子樹也分別為二叉查詢樹;
  4. 沒有鍵值相等的節點。

二叉搜尋樹的中序遍歷結果是元素值由小到大有序的嗎?這題要求把每個結點的值更新為比其大的結點值之和,那倒著來一遍中序遍歷就好了。也就是說,由大到小遍歷結點,每次累加比當前結點值大的和,賦值給當前結點就好了“右 - 根 - 左”順序遍歷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