题目浅析

  • 想查看原题可以点击题目链接

  • 简单地说,就是给一个二叉树,要求根到每个叶子节点的路径。

思路分享

代码解答(强烈建议自行解答后再看)

  • 参考题解
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# 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]:
ans = []
cur = []
def dfs(root:Optional[TreeNode]):
if not root:
return
nonlocal cur
cur.append(str(root.val))
# print(root.val, cur)
if not root.left and not root.right:
nonlocal ans
ans.append("->".join(cur))
else:
dfs(root.left)
dfs(root.right)
cur.pop()
# print(root.val, cur)
dfs(root)
return ans