1038. 从二叉搜索树到更大和树

刚开始的思路,先遍历求和,在通过先序遍历一个个求解,但是因为无法记录和的值,只能告吹。

错误解法(记录下来是因为熟悉bfs,以及python中没有和c++中int &一样的语法的问题,需要牢记。):

class Solution:
    def bstToGst(self, root: TreeNode) -> TreeNode:
        s = self.bst(root)
        s1 = 0
        self.Inorder(root,s,s1)        
        return root
        
    def Inorder(self,root,s,s1):
        if root == None:
            return
        
        self.Inorder( root.left,s,s1)
        
        s1 = s1 + root.val
        root.val = s -s1+ root.val
       
        
        self.Inorder(root.right,s,s1)
        
        
        
        
    def bst(self, root: TreeNode) -> TreeNode:
        tree_sum = 0
        if root is None:
            return tree_sum
        queue = [root]
        while queue:
            cur_node = queue.pop(0)
            tree_sum += cur_node.val
            if cur_node.left is not None:
                queue.append(cur_node.left)
            if cur_node.right is not None:
                queue.append(cur_node.right)
        return tree_sum

你可能感兴趣的:(1038. 从二叉搜索树到更大和树)