Print the first shortest root to leaf path in a Binary Tree

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.
Efficient Approach:
- Create a struct Node with left and right pointers and a data value.
- Create a function newNode that creates a new binary tree node and initializes its data and pointers to null.
- Create a recursive function printPath that takes in the data value of a node and a parent map, and prints the path from that node to the root using the parent map. The parent map is a hash map that maps a node’s data value to its parent’s data value.
- Create a function leftMostShortest that takes in a root node and performs a level order traversal of the binary tree until it finds the first leaf node. It uses a queue to keep track of the nodes to visit and a parent map to keep track of the parent of each node. When it finds the first leaf node, it calls the printPath function to print the path from the leaf node to the root.
- In the main function, create a binary tree using the newNode function, and call the leftMostShortest function with the root node.
Below is the implementation of the above approach:
C++
// C++ program to print first shortest// root to leaf path#include <bits/stdc++.h>using namespace std;Â
// Binary tree nodestruct Node {Â Â Â Â struct Node* left;Â Â Â Â struct Node* right;Â Â Â Â int data;};Â
// Function to create a new// Binary nodestruct Node* newNode(int data){Â Â Â Â struct Node* temp = new Node;Â
    temp->data = data;    temp->left = NULL;    temp->right = NULL;Â
    return temp;}Â
// Recursive function used by leftMostShortest// to print the first shortest root to leaf pathvoid printPath(int Data, unordered_map<int,                             int> parent){    // If the root's data is same as    // its parent data then return    if (parent[Data] == Data)        return;Â
    // Recur for the function printPath    printPath(parent[Data], parent);Â
    // Print the parent node's data    cout << parent[Data] << " ";}Â
// Function to perform level order traversal// until we find the first leaf nodevoid leftMostShortest(struct Node* root){    // Queue to store the nodes    queue<struct Node*> q;Â
    // Push the root node    q.push(root);Â
    // Initialize the value of first    // leaf node to occur as -1    int LeafData = -1;Â
    // To store the current node    struct Node* temp = NULL;Â
    // Map to store the parent node's data    unordered_map<int, int> parent;Â
    // Parent of root data is set as it's    // own value    parent[root->data] = root->data;Â
    // We store first node of the smallest level    while (!q.empty()) {        temp = q.front();        q.pop();Â
        // If the first leaf node has been found        // set the flag variable as 1        if (!temp->left && !temp->right) {            LeafData = temp->data;            break;        }        else {Â
            // If current node has left            // child, push in the queue            if (temp->left) {                q.push(temp->left);Â
                // Set temp's left node's parent as temp                parent[temp->left->data] = temp->data;            }Â
            // If current node has right            // child, push in the queue            if (temp->right) {                q.push(temp->right);Â
                // Set temp's right node's parent                // as temp                parent[temp->right->data] = temp->data;            }        }    }Â
    // Recursive function to print the first     // shortest root to leaf path    printPath(LeafData, parent);Â
    // Print the leaf node of the first    // shortest path    cout << LeafData << " ";}Â
// Driver codeint main(){Â Â Â Â struct Node* root = newNode(1);Â Â Â Â root->left = newNode(2);Â Â Â Â root->right = newNode(3);Â Â Â Â root->left->left = newNode(4);Â Â Â Â root->right->left = newNode(5);Â Â Â Â root->right->right = newNode(7);Â Â Â Â root->left->left->left = newNode(10);Â Â Â Â root->left->left->right = newNode(11);Â Â Â Â root->right->right->left = newNode(8);Â
    leftMostShortest(root);Â
    return 0;} |
Java
// Java program to print first shortest// root to leaf pathimport java.util.*;Â
class GFG{Â
// Binary tree nodestatic class Node{Â Â Â Â Node left;Â Â Â Â Node right;Â Â Â Â int data;};Â
// Function to create a new// Binary nodestatic Node newNode(int data){Â Â Â Â Node temp = new Node();Â
    temp.data = data;    temp.left = null;    temp.right = null;Â
    return temp;}Â
// Recursive function used by leftMostShortest// to print the first shortest root to leaf pathstatic void printPath(int Data,                      HashMap<Integer,                               Integer> parent) {         // If the root's data is same as    // its parent data then return    if (parent.get(Data) == Data)        return;Â
    // Recur for the function printPath    printPath(parent.get(Data), parent);Â
    // Print the parent node's data    System.out.print(parent.get(Data) + " ");}Â
// Function to perform level order traversal// until we find the first leaf nodestatic void leftMostShortest(Node root){         // Queue to store the nodes    Queue<Node> q = new LinkedList<>();Â
    // Add the root node    q.add(root);Â
    // Initialize the value of first    // leaf node to occur as -1    int LeafData = -1;Â
    // To store the current node    Node temp = null;Â
    // Map to store the parent node's data    HashMap<Integer,             Integer> parent = new HashMap<>();Â
    // Parent of root data is set as it's    // own value    parent.put(root.data, root.data);Â
    // We store first node of the smallest level    while (!q.isEmpty())    {        temp = q.poll();Â
        // If the first leaf node has been found        // set the flag variable as 1        if (temp.left == null &&            temp.right == null)        {            LeafData = temp.data;            break;        }         else        {Â
            // If current node has left            // child, add in the queue            if (temp.left != null)             {                q.add(temp.left);Â
                // Set temp's left node's parent                 // as temp                parent.put(temp.left.data,                            temp.data);            }Â
            // If current node has right            // child, add in the queue            if (temp.right != null)            {                q.add(temp.right);Â
                // Set temp's right node's parent                // as temp                parent.put(temp.right.data,                                  temp.data);            }        }    }Â
    // Recursive function to print the     // first shortest root to leaf path    printPath(LeafData, parent);Â
    // Print the leaf node of the first    // shortest path    System.out.println(LeafData + " ");}Â
// Driver Codepublic static void main(String[] args){Â Â Â Â Node root = newNode(1);Â Â Â Â root.left = newNode(2);Â Â Â Â root.right = newNode(3);Â Â Â Â root.left.left = newNode(4);Â Â Â Â root.right.left = newNode(5);Â Â Â Â root.right.right = newNode(7);Â Â Â Â root.left.left.left = newNode(10);Â Â Â Â root.left.left.right = newNode(11);Â Â Â Â root.right.right.left = newNode(8);Â
    leftMostShortest(root);}}Â
// This code is contributed by sanjeev2552 |
Python3
# Python3 program to print first # shortest root to leaf path Â
# Binary tree node class Node:         def __init__(self, data):        self.data = data        self.left = None        self.right = NoneÂ
# Recursive function used by leftMostShortest # to print the first shortest root to leaf path def printPath(Data, parent): Â
    # If the root's data is same as     # its parent data then return     if parent[Data] == Data:         returnÂ
    # Recur for the function printPath     printPath(parent[Data], parent) Â
    # Print the parent node's data     print(parent[Data], end = " ") Â
# Function to perform level order traversal # until we find the first leaf node def leftMostShortest(root): Â
    # Queue to store the nodes     q = [] Â
    # Push the root node     q.append(root) Â
    # Initialize the value of first     # leaf node to occur as -1     LeafData = -1Â
    # To store the current node     temp = NoneÂ
    # Map to store the parent node's data     parent = {} Â
    # Parent of root data is set     # as it's own value     parent[root.data] = root.data Â
    # We store first node of the     # smallest level     while len(q) != 0:         temp = q.pop(0)Â
        # If the first leaf node has been         # found set the flag variable as 1         if not temp.left and not temp.right:             LeafData = temp.data             break                 else:                          # If current node has left             # child, push in the queue             if temp.left:                 q.append(temp.left) Â
                # Set temp's left node's parent as temp                 parent[temp.left.data] = temp.data Â
            # If current node has right             # child, push in the queue             if temp.right:                q.append(temp.right) Â
                # Set temp's right node's parent                 # as temp                 parent[temp.right.data] = temp.data Â
    # Recursive function to print the first     # shortest root to leaf path     printPath(LeafData, parent) Â
    # Print the leaf node of the     # first shortest path     print(LeafData, end = " ")Â
# Driver code if __name__ == "__main__": Â
    root = Node(1)     root.left = Node(2)     root.right = Node(3)     root.left.left = Node(4)     root.right.left = Node(5)     root.right.right = Node(7)     root.left.left.left = Node(10)     root.left.left.right = Node(11)     root.right.right.left = Node(8) Â
    leftMostShortest(root) Â
# This code is contributed by Rituraj Jain |
C#
// C# program to print first shortest// root to leaf pathusing System;using System.Collections; using System.Collections.Generic;Â
class GFG{  // Binary tree nodepublic class Node{    public Node left;    public Node right;    public int data;};  // Function to create a new// Binary nodepublic static Node newNode(int data){    Node temp = new Node();      temp.data = data;    temp.left = null;    temp.right = null;      return temp;}  // Recursive function used by leftMostShortest// to print the first shortest root to leaf pathstatic void printPath(int Data,            Dictionary<int, int> parent) {          // If the root's data is same as    // its parent data then return    if (parent[Data] == Data)        return;      // Recur for the function printPath    printPath(parent[Data], parent);      // Print the parent node's data    Console.Write(parent[Data] + " ");}  // Function to perform level order traversal// until we find the first leaf nodestatic void leftMostShortest(Node root){          // Queue to store the nodes    Queue q = new Queue();      // Add the root node    q.Enqueue(root);      // Initialize the value of first    // leaf node to occur as -1    int LeafData = -1;      // To store the current node    Node temp = null;      // Map to store the parent node's data    Dictionary<int,               int> parent = new Dictionary<int,                                             int>();      // Parent of root data is set as it's    // own value    parent[root.data] = root.data;      // We store first node of the     // smallest level    while (q.Count != 0)    {        temp = (Node)q.Dequeue();          // If the first leaf node has been         // found set the flag variable as 1        if (temp.left == null &&           temp.right == null)        {            LeafData = temp.data;            break;        }         else        {              // If current node has left            // child, add in the queue            if (temp.left != null)             {                q.Enqueue(temp.left);                  // Set temp's left node's parent                 // as temp                parent[temp.left.data] = temp.data;            }              // If current node has right            // child, add in the queue            if (temp.right != null)            {                q.Enqueue(temp.right);                  // Set temp's right node's parent                // as temp                parent[temp.right.data] = temp.data;            }        }    }      // Recursive function to print the     // first shortest root to leaf path    printPath(LeafData, parent);      // Print the leaf node of the first    // shortest path    Console.Write(LeafData + " ");}  // Driver Codepublic static void Main(string[] args){    Node root = newNode(1);    root.left = newNode(2);    root.right = newNode(3);    root.left.left = newNode(4);    root.right.left = newNode(5);    root.right.right = newNode(7);    root.left.left.left = newNode(10);    root.left.left.right = newNode(11);    root.right.right.left = newNode(8);      leftMostShortest(root);}}Â
// This code is contributed by rutvik_56 |
Javascript
<script>Â
    // JavaScript program to print first     // shortest root to leaf path         // Binary tree node    class Node    {        constructor(data) {           this.left = null;           this.right = null;           this.data = data;        }    }         // Function to create a new    // Binary node    function newNode(data)    {        let temp = new Node(data);        return temp;    }Â
    // Recursive function used by leftMostShortest    // to print the first shortest root to leaf path    function printPath(Data, parent)    {Â
        // If the root's data is same as        // its parent data then return        if (parent.get(Data) == Data)            return;Â
        // Recur for the function printPath        printPath(parent.get(Data), parent);Â
        // Print the parent node's data        document.write(parent.get(Data) + " ");    }Â
    // Function to perform level order traversal    // until we find the first leaf node    function leftMostShortest(root)    {Â
        // Queue to store the nodes        let q = [];Â
        // Add the root node        q.push(root);Â
        // Initialize the value of first        // leaf node to occur as -1        let LeafData = -1;Â
        // To store the current node        let temp = null;Â
        // Map to store the parent node's data        let parent = new Map();Â
        // Parent of root data is set as it's        // own value        parent.set(root.data, root.data);Â
        // We store first node of the smallest level        while (q.length > 0)        {            temp = q[0];            q.shift();Â
            // If the first leaf node has been found            // set the flag variable as 1            if (temp.left == null &&                temp.right == null)            {                LeafData = temp.data;                break;            }            else            {Â
                // If current node has left                // child, add in the queue                if (temp.left != null)                {                    q.push(temp.left);Â
                    // Set temp's left node's parent                    // as temp                    parent.set(temp.left.data,                               temp.data);                }Â
                // If current node has right                // child, add in the queue                if (temp.right != null)                {                    q.push(temp.right);Â
                    // Set temp's right node's parent                    // as temp                    parent.set(temp.right.data,                                     temp.data);                }            }        }Â
        // Recursive function to print the        // first shortest root to leaf path        printPath(LeafData, parent);Â
        // Print the leaf node of the first        // shortest path        document.write(LeafData + " ");    }         let root = newNode(1);    root.left = newNode(2);    root.right = newNode(3);    root.left.left = newNode(4);    root.right.left = newNode(5);    root.right.right = newNode(7);    root.left.left.left = newNode(10);    root.left.left.right = newNode(11);    root.right.right.left = newNode(8);      leftMostShortest(root);Â
</script> |
Output:Â
1 3 5
Â
Time Complexity: O(N)Â
Auxiliary Space: O(N)
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



