力扣129. 求根到叶子节点数字之和

原题

 1 class Solution:
 2     ans = 0
 3     def sumNumbers(self, root: TreeNode) -> int:
 4         def dfs(root,n):
 5             if not root:return 
 6             n *= 10
 7             n += root.val
 8             if not root.left and not root.right:
 9                 self.ans += n
10                 return
11             dfs(root.left,n)
12             dfs(root.right,n)
13         dfs(root,0)
14         return self.ans

 

posted @ 2021-01-24 20:50  凝视深空  阅读(80)  评论(0编辑  收藏  举报