#257
Binary Tree Paths
EasyStringBacktrackingTreeDepth-First SearchBinary TreeDepth-First SearchBacktracking
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution still uses depth-first search but avoids unnecessary string concatenations by using a list to build the path. This reduces the overhead of string operations and improves efficiency.
⚙️
Algorithm
4 steps- 1Step 1: Start from the root and initialize an empty list to store paths.
- 2Step 2: Use a recursive function to explore each node, appending the current node's value to a list.
- 3Step 3: If a leaf node is reached, convert the list to a string and add it to the paths list.
- 4Step 4: Backtrack to explore other branches of the tree.
solution.py21 lines
1# Full working Python code
2class TreeNode:
3 def __init__(self, val=0, left=None, right=None):
4 self.val = val
5 self.left = left
6 self.right = right
7
8class Solution:
9 def binaryTreePaths(self, root: TreeNode) -> List[str]:
10 paths = []
11 def dfs(node, path):
12 if node:
13 path.append(str(node.val))
14 if not node.left and not node.right:
15 paths.append('->'.join(path))
16 else:
17 dfs(node.left, path)
18 dfs(node.right, path)
19 path.pop()
20 dfs(root, [])
21 return pathsℹ
Complexity note: The time complexity is O(n) because we visit each node exactly once. The space complexity is O(n) due to the recursion stack and the storage of the paths.
- 1Understanding tree traversal is crucial for solving tree-related problems.
- 2Using lists for path construction can improve performance over string concatenation.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.