LeetCode 题解工作台
二叉树的所有路径
给你一个二叉树的根节点 root ,按 任意顺序 ,返回所有从根节点到叶子节点的路径。 叶子节点 是指没有子节点的节点。 示例 1: 输入: root = [1,2,3,null,5] 输出: ["1->2->5","1->3"] 示例 2: 输入: root = [1] 输出: ["1"] 提示:…
5
题型
5
代码语言
3
相关题
当前训练重点
简单 · 二分·树·traversal
答案摘要
我们可以使用深度优先搜索的方法遍历整棵二叉树,每一次我们将当前的节点添加到路径中。如果当前的节点是叶子节点,则我们将整个路径加入到答案中。否则我们继续递归遍历节点的孩子节点。最后当我们递归结束返回到当前节点时,我们需要将当前节点从路径中删除。 时间复杂度 ,空间复杂度 。其中 是二叉树的节点数。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·树·traversal 题型思路
题目描述
给你一个二叉树的根节点 root ,按 任意顺序 ,返回所有从根节点到叶子节点的路径。
叶子节点 是指没有子节点的节点。
示例 1:
输入:root = [1,2,3,null,5] 输出:["1->2->5","1->3"]
示例 2:
输入:root = [1] 输出:["1"]
提示:
- 树中节点的数目在范围
[1, 100]内 -100 <= Node.val <= 100
解题思路
方法一: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 binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
def dfs(root: Optional[TreeNode]):
if root is None:
return
t.append(str(root.val))
if root.left is None and root.right is None:
ans.append("->".join(t))
else:
dfs(root.left)
dfs(root.right)
t.pop()
ans = []
t = []
dfs(root)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(N) since every node is visited once, and constructing the path strings can also take O(N) per path. Space complexity is O(H) for recursion or stack storage, where H is the tree height, plus additional space for result strings. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Pay attention to leaf node identification to avoid missing paths.
- question_mark
Ensure string paths are constructed incrementally, not concatenated at the end only.
- question_mark
Watch for off-by-one errors in backtracking or path formatting with '->'.
常见陷阱
外企场景- error
Forgetting to backtrack when returning from recursion, leading to corrupted paths.
- error
Incorrectly identifying leaf nodes, which may skip paths or add incomplete strings.
- error
Using global or shared path state without copying, causing multiple paths to overlap incorrectly.
进阶变体
外企场景- arrow_right_alt
Return paths in reversed order or sorted lexicographically.
- arrow_right_alt
Generate paths as arrays of integers instead of string representations.
- arrow_right_alt
Handle trees where nodes may contain duplicate values but still track unique paths.