您的位置:首页 > 其它

【LEETCODE】257-Binary Tree Paths

2015-11-01 20:16 260 查看
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:

1
/ \
2 3
\
5

All root-to-leaf paths are:
["1->2->5", "1->3"]

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
self.ans = []

if root is None:
return self.ans

def dfs(root, path):
#if root is None:               #外函数已经判断root是否为空了,所以dfs不用再考虑root为空的时候
#return path
if root.left == root.right == None:
self.ans += path,           #一定要加逗号,否则是分开的
if root.left:
#self.ans += path
dfs(root.left, path + "->" + str(root.left.val))
if root.right:
dfs(root.right, path + "->" + str(root.right.val))     #此时path仍然是root的

dfs(root,str(root.val))

return self.ans
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: