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
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Print the longest path from root to leaf in a Binary tree
- Boundary Root to Leaf Path traversal of a Binary Tree
- Find the maximum sum leaf to root path in a Binary Tree
- Print the longest leaf to leaf path in a Binary tree
- Given a binary tree, print all root-to-leaf paths
- Given a binary tree, print out all of its root-to-leaf paths one per line.
- Shortest root to leaf path sum equal to a given number
- Print path from root to a given node in a binary tree
- Print path from root to all nodes in a Complete Binary Tree
- GCD from root to leaf path in an N-ary tree
- Maximum value of Bitwise AND 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
- 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
- Find if there is a pair in root to a leaf path with sum equals to root's data
- Sort the path from root to a given node in a Binary Tree
- Shortest path between two nodes in array like representation of binary tree
- Print Sum and Product of all Non-Leaf nodes in Binary Tree
- Print all leaf nodes of a Binary Tree from left to right
- Print the nodes of binary tree as they become the leaf node
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.
Improved By : rituraj_jain