【LEETCODE】257-Binary Tree Paths

来源:互联网 发布:福建医科大学网络教育 编辑:程序博客网 时间:2024/05/22 22:40

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 = Noneclass 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                     


0 0
原创粉丝点击