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