Introduction
Root to Leaf Paths means:
- finding every path
- from root node
- to leaf node
Leaf node means:
- node without children
Goal:
- store all possible paths
inside binary tree
Example:
1/ \
2 3
\
5
Paths:
1 → 2 → 5
1 → 3
Explanation:
Every path starts from root node and ends at leaf node.This problem is one of the most important applications of:
DFS Traversal Constraints
1 <= Number of Nodes <= 10^5Approach : Recursive DFS Solution
Explanations:
Explanation:
The idea is:
- traverse tree using DFS
- maintain current path
- store path at leaf node
Steps:
- Visit current node.
- Add node to path.
- Check leaf condition.
- Store complete path.
- Traverse left subtree.
- Traverse right subtree.
- Backtrack path.
Leaf Condition:
left == null and right == nullThis approach:
- uses DFS recursion
- performs path tracking
- uses backtracking
Dry Run
Visit:1
Current path:
1
Visit:
2
Current path:
1 → 2
Visit:
5
Leaf node reached.
Store:
1 → 2 → 5
Backtrack and continue.
Practice :
Complexity Analysis
Time Complexity:- O(n)Explanation : Every tree node is visited once.
Space Complexity:- O(h)
Explanation : Recursion stack depends on tree height.