LeetCode--257--二叉树的所有路径

问题描述:

给定一个二叉树,返回所有从根节点到叶子节点的路径。

说明: 叶子节点是指没有子节点的节点。

示例:

输入:

   1
 /   
2     3
 
  5

输出: ["1->2->5", "1->3"]

解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3

方法:(整不明白什么时候是None)

 1 class Solution(object):
 2     def binaryTreePaths(self, root):
 3         """
 4         :type root: TreeNode
 5         :rtype: List[str]
 6         """
 7         path = ""
 8         res = []
 9         self.TreePath(root,path,res)
10         return res
11     
12     def TreePath(self,root,path,res):
13         if root is None:
14             return
15         path += str(root.val)
16         if root.left is not None:
17             self.TreePath(root.left,path+"->",res)
18         if root.right is not None:
19             self.TreePath(root.right,path+"->",res)
20         if root.left is None and root.right is None:
21             res.append(path)

2018-09-22 16:14:13(蒙蔽状态)

原文地址:https://www.cnblogs.com/NPC-assange/p/9690355.html