天天看點

【LeetCode538】把二叉搜尋樹轉換為累加樹(BST中序)

1.題目

【LeetCode538】把二叉搜尋樹轉換為累加樹(BST中序)

2.思路

3.代碼

# 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: TreeNode) -> TreeNode:
        def dfs(root: TreeNode):
            nonlocal total  # 用外面的total
            if root:
                dfs(root.right)
                total += root.val
                root.val = total
                dfs(root.left)

        total = 0
        dfs(root) # 一定注意這是二叉搜尋樹,存儲的值有規律!
        return