↓Skip to main content
  1. LeetCode/

LeetCode 257: Binary Tree Paths

·1 min· ·
LeetCode Easy String Backtracking Tree Depth-First-Search
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-22

  • Submissions: Runtime Error ×3 → Accepted ×2

Approach
#

Pass the path down during DFS (Tree Template 1); at a leaf it is a complete path. Values are integers, so convert with str() before joining.

My Attempts
#

The first three versions all raised TypeError by adding the integer node.val directly to the string "->".

Solution
#

class Solution:
    def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
        res = []
        def dfs(node, path):
            if not node:
                return
            path = path + [str(node.val)]
            if not node.left and not node.right:
                res.append("->".join(path))
            dfs(node.left, path)
            dfs(node.right, path)
        dfs(root, [])
        return res

Complexity
#

Time O(n · h), space O(h).

Mistakes to Avoid
#

  • Integers cannot be concatenated with strings; use str() first.

Interview Explanation
#

I DFS with the current path and, at each leaf, join it with -> into the answer. Time O(n · h).

Related

LeetCode 226: Invert Binary Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 226 note: swap every node’s children, using a simultaneous assignment so the already-changed side is not reused
LeetCode 145: Binary Tree Postorder Traversal
·2 mins
LeetCode Easy Stack Tree Depth-First-Search Binary-Tree
LeetCode 145 note: iterative post-order pushes a node back with a visited flag on its first pop, then the right and left children; record it on the second pop
LeetCode 110: Balanced Binary Tree
·2 mins
LeetCode Easy Tree Depth-First-Search Binary-Tree
LeetCode 110 note: every node’s subtree heights must differ by at most 1; return heights in post-order and propagate -1 once unbalanced
LeetCode 111: Minimum Depth of Binary Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 111 note: minimum depth must end at a leaf; with only one child, the empty side (depth 0) cannot count as the minimum
LeetCode 112: Path Sum
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 112 note: subtract each value from targetSum on the way down; it works if the remainder matches at a leaf
LeetCode 100: Same Tree
·1 min
LeetCode Easy Tree Depth-First-Search Breadth-First-Search Binary-Tree
LeetCode 100 note: two empty trees are equal, one empty and one not differ, and otherwise compare values and recurse on both sides