|
| 1 | +""" |
| 2 | +Problem Link: https://leetcode.com/problems/binary-tree-paths/ |
| 3 | + |
| 4 | +Given the root of a binary tree, return all root-to-leaf paths in any order. |
| 5 | +A leaf is a node with no children. |
| 6 | + |
| 7 | +Example 1: |
| 8 | + |
| 9 | +Input: root = [1,2,3,null,5] |
| 10 | +Output: ["1->2->5","1->3"] |
| 11 | + |
| 12 | +Example 2: |
| 13 | +Input: root = [1] |
| 14 | +Output: ["1"] |
| 15 | + |
| 16 | +Constraints: |
| 17 | +The number of nodes in the tree is in the range [1, 100]. |
| 18 | +-100 <= Node.val <= 100 |
| 19 | +""" |
| 20 | +# Definition for a binary tree node. |
| 21 | +# class TreeNode: |
| 22 | +# def __init__(self, val=0, left=None, right=None): |
| 23 | +# self.val = val |
| 24 | +# self.left = left |
| 25 | +# self.right = right |
| 26 | +class Solution: |
| 27 | + def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]: |
| 28 | + if not root: |
| 29 | + return [] |
| 30 | + return self.helper(root, [], []) |
| 31 | + |
| 32 | + def helper(self, root, res, cur_path): |
| 33 | + if not root: |
| 34 | + return res |
| 35 | + |
| 36 | + cur_path.append(str(root.val)) |
| 37 | + if not root.left and not root.right: |
| 38 | + res.append("->".join(cur_path)) |
| 39 | + |
| 40 | + self.helper(root.left, res, cur_path) |
| 41 | + self.helper(root.right, res, cur_path) |
| 42 | + cur_path.pop() |
| 43 | + return res |
0 commit comments