心路历程:
二分搜索树 == 中序遍历,记住这一点即可;
两次遍历,第一次求和,第二次赋值即可
注意的点:
1、注意赋值的时候需要包含node.val,相当于包含i的后缀和
解法:DFS
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
# 两次遍历即可,第二次必须是中序
res = 0
def dfs1(node):
nonlocal res
if not node:
return
res += node.val
dfs1(node.left)
dfs1(node.right)
dfs1(root)
def dfs2(node):
nonlocal res
if not node:
return
dfs2(node.left)
t = res - node.val
node.val = res
res = t
dfs2(node.right)
dfs2(root)
return root