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
思路:看了discuss里面的提示,写了这个方法.思路比较清晰,用递归的方法,先列出终止条件1.root为空 2.没有左右孩子(叶子节点)
有问题的是在于两个递归一个用'=',一个用'+='.这是因为需要返回所有root到leaf的路径,如果两个都是'='的话,只能返回一条路径.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
if not root:
return []
if not root.left and not root.right:
return [str(root.val)]
path = [str(root.val)+'->' + p for p in self.binaryTreePaths(root.left)]
path += [str(root.val)+'->' + p for p in self.binaryTreePaths(root.right)]
return path

本文介绍了一种基于递归的二叉树路径查找算法,该算法能够有效地找到从根节点到叶节点的所有路径。通过定义终止条件和递归过程,算法能够清晰地处理二叉树结构,并返回所有符合条件的路径。
422

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



