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 3
Output: 25
Explanation:
The root-to-leaf path 1->2
represents the number 12.
The root-to-leaf path 1->3
represents the number 13
Therefore, 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

本文介绍了一种使用深度优先搜索(DFS)算法解决二叉树路径之和问题的方法。通过遍历二叉树,计算从根节点到叶节点的所有路径数值之和。示例中,输入为[1,2,3]的二叉树,输出为25,解释了1->2和1->3两条路径分别代表的数值12和13。
1569

被折叠的 条评论
为什么被折叠?



