欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

LeetCode] 利特码Sword to Offer II 049.根节点到叶节点的路径编号总和

最编程 2024-05-22 12:04:38
...
# 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 sumNumbers(self, root: TreeNode) -> int:
res = []
num = []
self.dfs(root,num,res)
# print(res)
out = list(map(int,res))
return sum(out)
def dfs(self,root,num,res):
num.append(str(root.val)) #
if root.left is None and root.right is None: # 说明是叶子节点
# print(num)
res.append("".join(num))
num.pop()
return
if root.left:
self.dfs(root.left,num,res)
if root.right:
self.dfs(root.right,num,res)
num.pop()