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
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.
- Given a binary tree, print all root-to-leaf paths
- Print all root to leaf paths with there relative positions
- Given a binary tree, print out all of its root-to-leaf paths one per line.
- Sum of all the numbers that are formed from root to leaf paths
- Remove nodes on root to leaf paths of length < K
- Count of Root to Leaf Paths consisting of at most M consecutive Nodes having value K
- Count the number of paths from root to leaf of a Binary tree with given XOR value
- Count of root to leaf paths in a Binary Tree that form an AP
- Root to leaf paths having equal lengths in a Binary Tree
- Count of root to leaf paths whose permutation is palindrome in a Binary Tree
- Print all the paths from root, with a specified sum in Binary tree
- Print the path common to the two paths from the root to the two given nodes
- Print the first shortest root to leaf path in a Binary Tree
- Print the longest path from root to leaf in a Binary tree
- Find if there is a pair in root to a leaf path with sum equals to root's data
- Print the longest leaf to leaf path in a Binary tree
- GCD from root to leaf path in an N-ary tree
- Check if there is a root to leaf path with given sequence
- Root to leaf path sum equal to a given number
- Root to leaf path product equal to a given number