- 解法1(T93% S38%):对于二叉树还是经典的递归方法,嵌套一个函数用于递归子树。如果是空节点则直接返回;如果是叶则添加最后一个值并把完整的字符串加到结果里;否则把当前值加到字符串里并添加
→接着递归左右子树
class Solution(object):
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
res = []
def binarySubTreePath(root, pathstr):
if not root: return
if not root.left and not root.right:
res.append(pathstr+str(root.val))
return
pathstr += str(root.val)+"->"
binarySubTreePath(root.left, pathstr)
binarySubTreePath(root.right, pathstr)
binarySubTreePath(root, "")
return
该博客介绍了如何使用Python解决二叉树的所有路径问题。通过递归方法,遍历二叉树的每个节点,当遇到叶子节点时,将路径添加到结果列表中。代码实现清晰,适用于理解二叉树的遍历。
1970

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



