题解 | #将二叉搜索树改为累加树#

将二叉搜索树改为累加树

http://www.nowcoder.com/practice/19bff16ca0d64d6da38ed24fd2903ce9

dfs, 以 右->根->左 的顺序进行叠加, 每次叠加时需要加上之前的值总和, 则设置一个全局变量记录

# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param root TreeNode类 
# @return TreeNode类
#
class Solution:
    def convertBST(self , root: TreeNode) -> TreeNode:
        # write code here
        total = 0
        def dfs(root):
            nonlocal total
            if not root:
                return
            dfs(root.right)
            total += root.val
            root.val = total
            dfs(root.left)
        dfs(root)
        return root
全部评论

相关推荐

A_SOUL_Off...:疑似加班加出幻觉了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务