还是采用的将根到叶全列出来的方法来做的。一个思路可以做4道题。。。代码如下:
# 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]
"""
pathlist = []
def showpath(list1, root):
if not root:
return []
list2 = list1[::]
if list2 == []:
list2.append(root.val)
else:
list2.append(root.val)
if not root.left and not root.right:
pathlist.append(list2)
else:
if root.left:
list1 = list2
showpath(list1, root.left)
if root.right:
list1 = list2
showpath(list1, root.right)
return pathlist
s = showpath([], root)
if s == []:
return []
for i in range(len(s)):
for j in range(len(s[i])):
s[i][j] = str(s[i][j])
for i in range(len(s)):
s[i] = '->'.join(s[i])
return s