257. 二叉树的所有路径
题目
给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。
示例:1
2
3
4
5
6
7
8
9输入:
   1
 /   \
2     3
 \
  5
输出: ["1->2->5", "1->3"]
解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
方法
方法1:递归
递归先序遍历1
2
3
4
5
6
7
8
9
10
11
12
13class Solution(object):
    def binaryTreePaths(self, root):
        """
        :type root: TreeNode
        :rtype: List[str]
        """
        if not root:
            return []
        if not root.left and not root.right:
            return [str(root.val)]
        left_paths=self.binaryTreePaths(root.left)
        right_paths=self.binaryTreePaths(root.right)
        return ['%s->%s' %(root.val,path) for path in left_paths+right_paths]
| 1 | # Definition for a binary tree node. | 
| 1 | # Definition for a binary tree node. | 
| 1 | # Definition for a binary tree node. | 
方法2:迭代
| 1 | # Definition for a binary tree node. |