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

解题思路

树的深度优先遍历,将路径的值十进制加乘起来
碰到叶子结点的时候返回完整的数字
细节如实现

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

代码

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None


class Solution:
    def sumNumbers(self, root: TreeNode) -> int:
        return sum(dfs(root, 0))

def dfs(tree, p):
    if not tree: return []
    if is_leaf(tree): return [p*10 + tree.val]
    return [*dfs(tree.left, p*10 + tree.val), *dfs(tree.right, p*10 + tree.val)]

def is_leaf(node):
    return node and not node.left and not node.right

效果图

你可能感兴趣的:(129. 求根节点到叶节点数字之和)