Skip to content

Latest commit

 

History

History
50 lines (38 loc) · 1.15 KB

0257. Binary Tree Paths.md

File metadata and controls

50 lines (38 loc) · 1.15 KB

题目

Given a binary tree, return all root-to-leaf paths.

Note: A leaf is a node with no children.

Example:

Input:

   1
 /   \
2     3
 \
  5

Output: ["1->2->5", "1->3"]

Explanation: All root-to-leaf paths are: 1->2->5, 1->3

我的思路

这道题要求返回所有从根节点到叶子节点的路径,我想到用递归来完成。记录下途中的节点,遇到叶子节点时生成一条字符串路径。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def binaryTreePaths(self, root: TreeNode) -> List[str]:
        res = []
        s = ""
        if not root:
            return res
        if not root.left and not root.right:
            res.append(str(root.val))
            return res
        
        for x in self.binaryTreePaths(root.left):
            res.append(str(root.val)+"->"+x)
        for x in self.binaryTreePaths(root.right):
            res.append(str(root.val)+"->"+x)
        return res