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
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
- Find the maximum sum leaf to root path in a Binary Tree
- Boundary Root to Leaf Path traversal of 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
- 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
- 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 all leaf nodes of a binary tree from right to left
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.
Improved By : rituraj_jain