LeetCode 题解工作台
求根节点到叶节点数字之和
给你一个二叉树的根节点 root ,树中每个节点都存放有一个 0 到 9 之间的数字。 每条从根节点到叶节点的路径都代表一个数字: 例如,从根节点到叶节点的路径 1 -> 2 -> 3 表示数字 123 。 计算从根节点到叶节点生成的 所有数字之和 。 叶节点 是指没有子节点的节点。 示例 1: 输…
3
题型
8
代码语言
3
相关题
当前训练重点
中等 · 二分·树·traversal
答案摘要
我们可以设计一个函数 $dfs(root, s)$,表示从当前节点 出发,且当前路径数字为 ,返回从当前节点到叶子节点的所有路径数字之和。那么答案就是 $dfs(root, 0)$。 函数 $dfs(root, s)$ 的计算如下:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·树·traversal 题型思路
题目描述
root ,树中每个节点都存放有一个 0 到 9 之间的数字。
每条从根节点到叶节点的路径都代表一个数字:
- 例如,从根节点到叶节点的路径
1 -> 2 -> 3表示数字123。
计算从根节点到叶节点生成的 所有数字之和 。
叶节点 是指没有子节点的节点。
示例 1:
输入:root = [1,2,3] 输出:25 解释: 从根到叶子节点路径1->2代表数字12从根到叶子节点路径1->3代表数字13因此,数字总和 = 12 + 13 =25
示例 2:
输入:root = [4,9,0,5,1] 输出:1026 解释: 从根到叶子节点路径4->9->5代表数字 495 从根到叶子节点路径4->9->1代表数字 491 从根到叶子节点路径4->0代表数字 40 因此,数字总和 = 495 + 491 + 40 =1026
提示:
- 树中节点的数目在范围
[1, 1000]内 0 <= Node.val <= 9- 树的深度不超过
10
解题思路
方法一:DFS
我们可以设计一个函数 ,表示从当前节点 出发,且当前路径数字为 ,返回从当前节点到叶子节点的所有路径数字之和。那么答案就是 。
函数 的计算如下:
- 如果当前节点 为空,则返回 。
- 否则,将当前节点的值加到 中,即 。
- 如果当前节点是叶子节点,则返回 。
- 否则,返回 。
时间复杂度 ,空间复杂度 。其中 是二叉树的节点数。
# 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: Optional[TreeNode]) -> int:
def dfs(root, s):
if root is None:
return 0
s = s * 10 + root.val
if root.left is None and root.right is None:
return s
return dfs(root.left, s) + dfs(root.right, s)
return dfs(root, 0)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Do you understand how DFS is applied to track root-to-leaf paths?
- question_mark
Can you explain how you would modify your approach if the tree had more complex node values?
- question_mark
Are you able to handle edge cases where the tree has only one node?
常见陷阱
外企场景- error
Not properly tracking the current number as you traverse the tree, leading to incorrect sums.
- error
Forgetting to add the number formed at the leaf node to the final sum.
- error
Confusing binary-tree traversal approaches, such as mixing up DFS with BFS, or not accounting for recursion depth.
进阶变体
外企场景- arrow_right_alt
Sum of all paths that lead to the leaf nodes of a n-ary tree.
- arrow_right_alt
Calculate the product instead of the sum of root-to-leaf numbers in a binary tree.
- arrow_right_alt
Find the maximum root-to-leaf number formed in a binary tree.