码迷,mamicode.com
首页 > 其他好文 > 详细

257. Binary Tree Paths 二叉树路径

时间:2017-07-08 13:25:16      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:ack   tree node   null   one   title   ref   span   ace   class   

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"]

  1. # Definition for a binary tree node.
  2. # class TreeNode(object):
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7. class Solution(object):
  8. def binaryTreePaths(self, root):
  9. if not root:
  10. return []
  11. result = []
  12. self.dfs(root, result, "")
  13. return result
  14. def dfs(self, node, result, string):
  15. if not node.left and not node.right:
  16. result.append(string + str(node.val))
  17. if node.left:
  18. self.dfs(node.left, result, string + str(node.val) + "->")
  19. if node.right:
  20. self.dfs(node.right, result, string + str(node.val) + "->")







257. Binary Tree Paths 二叉树路径

标签:ack   tree node   null   one   title   ref   span   ace   class   

原文地址:http://www.cnblogs.com/xiejunzhao/p/a01c0c7c89ae8905dca777b29325a874.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!