Print root to leaf paths without using recursion
Given a binary tree, print all its root to leaf paths without using recursion. For example, consider the following Binary Tree.
6 / \ 3 5 / \ \ 2 5 4 / \ 7 4 There are 4 leaves, hence 4 root to leaf paths - 6->3->2 6->3->5->7 6->3->5->4 6->5>4
We strongly recommend you to minimize your browser and try this yourself first.
We can traverse tree iteratively (we have used iterative preorder). The question is, how to extend the traversal to print root to leaf paths? The idea is to maintain a map to store parent pointers of binary tree nodes. Now whenever we encounter a leaf node while doing iterative preorder traversal, we can easily print root to leaf path using parent pointer. Below is implementation of this idea.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
10 8 3 10 8 5 10 2 2
This article is contributed by Aditya Goel. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above