原题链接https://leetcode.com/problems/binary-tree-paths/
做到这里的时候已经被前面的dfs的题弄到心力憔悴,这题回了口血,啊哈哈哈
Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:
Input:
1
/ \
2 3
\
5
Output: ["1->2->5", "1->3"]
Explanation: All root-to-leaf paths are: 1->2->5, 1->3
class Solution:
def binaryTreePaths(self, root: TreeNode) -> List[str]:
def dfs(root, path, res):
if not root:
return
path = path + "->" + str(root.val)
if not (root.left or root.right):
res.append(path[2:])
dfs(root.left,path,res)
dfs(root.right,path,res)
path = ""
res = []
dfs(root,path,res)
return res
网友评论