Solution Review: Print All the Paths
Understand how to implement a depth-first traversal to print every path from the root to leaf nodes in a tree. This lesson guides you through using a stack to track nodes, printing paths at leaves, and managing recursion with efficient time and space complexity.
We'll cover the following...
Solution
For this problem, we’ll use a stack and follow the depth-first approach. Whenever we traverse a node, we’ll add that node to the stack. When we reach a leaf, we’ll print the whole list (from the root node to that leaf node). When we return from the function, we’ll remove the element that was added to the stack when we entered this function.
Solution code
Complexity analysis
The time and space complexity of this solution is .
Explanation
-
Lines 15 to 21: We start by pushing the current node to the stack. If the node we just pushed is a leaf, we print the path from root to this leaf by using
stk.Print(). Then we remove the current entry from the top of the stack to explore a sibling tree (if it exists) as shown in line 19. -
Lines 23–24: If the current node is not a leaf then we continue our tree traversal.
-
Line 26: At the end of the function, we pop the node from the stack which is explored fully.