Given a Binary Tree with distinct values, the task is to print the first smallest root to leaf path. We basically need to print the leftmost root to leaf path that has the minimum number of nodes.
Input: 1 / \ 2 3 / / \ 4 5 7 / \ \ 10 11 8 Output: 1 3 5 Input: 1 / \ 2 3 / / \ 40 5 7 \ 8 Output: 1 2 40
Approach: The idea is to use a queue to perform level order traversal, a map parent to store the nodes that will be present in the shortest path. Using level order traversal, we find the leftmost leaf. Once we find the leftmost leaf, we print path using the map.
Below is the implementation of the above approach:
1 3 5
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.
- Print the longest leaf to leaf path in a Binary tree
- Print the longest path from root to leaf in a Binary tree
- Shortest root to leaf path sum equal to a given number
- Find if there is a pair in root to a leaf path with sum equals to root's data
- Find the maximum sum leaf to root path in a Binary Tree
- Boundary Root to Leaf Path traversal of a Binary Tree
- Maximize count of set bits in a root to leaf path in a binary tree
- Find all root to leaf path sum of a Binary Tree
- Given a binary tree, print out all of its root-to-leaf paths one per line.
- Given a binary tree, print all root-to-leaf paths
- GCD from root to leaf path in an N-ary tree
- Print path from root to a given node in a binary tree
- Print path from root to all nodes in a Complete Binary Tree
- Count of root to leaf paths in a Binary Tree that form an AP
- Find maximum GCD value from root to leaf in a Binary tree
- Count the number of paths from root to leaf of a Binary tree with given XOR value
- Count root to leaf paths having exactly K distinct nodes in a Binary Tree
- Count of root to leaf paths whose permutation is palindrome in a Binary Tree
- Remove nodes from Binary Tree such that sum of all remaining root-to-leaf paths is atleast K
- Maximum value of Bitwise AND from root to leaf in a Binary tree
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.