您的位置:首页 > 编程语言 > Python开发

<LeetCode><Easy>257BinaryTreePaths (深度优先搜索)(列表深拷贝)

2015-10-14 16:23 676 查看
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"]


#Python2  48ms

# 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]
"""
paths=[]
if root is None:
return paths
def add(root,tList):    #Note that memory copy
tList.append(root.val)
status=1
if root.left:
lList=tList[:]    #deep copy
add(root.left,lList)
status=0
if root.right:
rList=tList[:]
add(root.right,rList)
status=0
if status:
paths.append("->".join([str(t) for t in tList]))
add(root,[])
return paths
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python leetcode