Skip to content

[257] Binary Tree Paths

https://leetcode.com/problems/binary-tree-paths/description/

  • algorithms
  • Easy (43.90%)
  • Source Code: 257.binary-tree-paths.py
  • Total Accepted: 218.9K
  • Total Submissions: 480.6K
  • Testcase Example: '[1,2,3,null,5]'

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

python
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def binaryTreePaths(self, root):
        """
        :type root: TreeNode
        :rtype: List[str]
        """
        path = []
        self.search_path(root, path, [])

        result = []
        for p in path:
            result.append('->'.join(p))

        return result

    def search_path(self, root, path, current):
        if not root: return
        current = current[:]
        current.append(str(root.val))
        if not root.left and not root.right:
            path.append(current)
            return
        else:
            if root.left:
                self.search_path(root.left, path, current)
            if root.right:
                self.search_path(root.right, path, current)

Last updated: