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.
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
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Print all pairs from two BSTs whose sum is greater than the given value
- Write a program to Calculate Size of a tree | Recursion
- Given a binary tree, print out all of its root-to-leaf paths one per line.
- The Great Tree-List Recursion Problem.
- Program to count leaf nodes in a binary tree
- Inorder Tree Traversal without Recursion
- Root to leaf path sum equal to a given number
- Inorder Tree Traversal without recursion and without stack!
- Given a binary tree, print all root-to-leaf paths
- Print nodes at k distance from root
- Print BST keys in the given range
- Print Ancestors of a given node in Binary Tree
- Find the maximum sum leaf to root path in a Binary Tree
- Print Postorder traversal from given Inorder and Preorder traversals
- Find depth of the deepest odd level leaf node