首页 > 其他 > 详细

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

时间:2018-09-22 22:44:00      阅读:181      评论:0      收藏:0      [点我收藏+]

问题描述:

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

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

示例:

输入:

   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(蒙蔽状态)

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!