LC129. 求根节点到叶节点数字之和

阅读 42

2022-04-06

先序遍历就行

def sumNumbers(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        def pre(root,pretotal):
            if not root:
                return 0
            total = pretotal*10 + root.val
            if not root.left and not root.right:
                return total
            return pre(root.left,total) + pre(root.right,total)
        return pre(root,0)

相关推荐

精彩评论(0)

0 0 举报