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