本文共 1134 字,大约阅读时间需要 3 分钟。
Given a binary tree containing digits from 0-9
only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3
which represents the number 123
.
Find the total sum of all root-to-leaf numbers.
Note: A leaf is a node with no children.
Example:
Input: [1,2,3] 1 / \ 2 3Output: 25Explanation:The root-to-leaf path 1->2 represents the number 12.The root-to-leaf path 1->3 represents the number 13Therefore, sum = 12 + 13 = 25.
用DFS的方法,用stack保存每个节点,以及从根节点到该节点所有的数。
如果这个当前节点是叶子节点,则用sum = val+sum*10去计算这个读数。
最后将所有读数加到一起即可。
class Solution: def sumNumbers(self, root: TreeNode) -> int: if root is None:return 0 stack=[(root, [root.val])] res=0 while stack: node, vallist=stack.pop(0) if node.left is None and node.right is None: sum=0 for val in vallist: sum = val+sum*10 res+=sum if node.left: stack.append((node.left, vallist+[node.left.val])) if node.right: stack.append((node.right, vallist+[node.right.val])) return res
转载地址:http://hdrbb.baihongyu.com/