LeetCode 538. Convert BST to Greater Tree (将 BST 转换为Greater树)

原题

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

Reference Answer

思路分析

BST的右子树都比该节点大,所以修改次序是右–>中–>左。用一个变量储存遍历过程中所有有节点之和就得到了所有的比当前把该节点的值更大的和,然后修改为该变量的值即可。

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def convertBST(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        self.node_sum = 0
        def reconstruct(root):
            if not root:
                return
            reconstruct(root.right)
            self.node_sum += root.val
            root.val = self.node_sum 
            reconstruct(root.left)
        
        # head = root
        reconstruct(root)
        return root
          

Note

  • 非常值得注意的是,如果直接传给调用函数 node_sum,即 def convertBST(self, root, node_sum) 结果是错误的, 因为通过传值,则调用时候回溯的过程中之前加上的值会被减去,不符合算法设计要求,算法希望加上一个值后就记录最新结果。
  • 另一个目前没搞明白的点是程序中:
self.node_sum += root.val
root.val = self.node_sum

若是修改为:

root.val = root.val + self.node_num
self.node_sum += root.val

思路是近似,无非是将加值过程后移了一步,但是结果是错误的,没搞明白,先mark一下吧。

参考文献

[1] https://blog.csdn.net/fuxuemingzhu/article/details/79132336

猜你喜欢

转载自blog.csdn.net/Dby_freedom/article/details/84981336