地址:点击打开链接
得到路径的时候判断一下叶节点,然后对是不是根节点判断一下,再用递归的方法
答案:
# 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]
"""
if root == None:
return []
if not root.left and not root.right:
return [str(root.val)]
self.pathList = []
self.getTreePath(root,'')
return self.pathList
def getTreePath(self,root,path):
if root == None:
return path
if not root.left and not root.right:
if path == '':
path = str(root.val)
else:
path += '->' + str(root.val)
self.pathList.append(path)
else:
if path == '':
path = str(root.val)
else:
path += '->' + str(root.val)
self.getTreePath(root.left, path )
self.getTreePath(root.right, path)