首页 > 代码库 > 257. Binary Tree Paths 二叉树路径

257. Binary Tree Paths 二叉树路径

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) + "->")





null


257. Binary Tree Paths 二叉树路径