Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
Sort the path from root to a given node in a Binary Tree
Next article icon

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

Last Updated : 25 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a Binary Tree with distinct values, the task is to find the first smallest root to leaf path. We basically need to find the leftmost root to leaf path that has the minimum number of nodes.

The root to leaf path in below image is 1-> 3 which is the leftmost root to leaf path that has the minimum number of nodes.

print-the-first-shortest-root-to-leaf-path-in-a-binary-tree


The root to leaf path in below image is 1-> 2 which is the leftmost root to leaf path that has the minimum number of nodes.

print-the-first-shortest-root-to-leaf-path-in-a-binary-tree-2

Approach:

The idea is to use a queue to perform level order traversal, a hashmap 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 hashmap

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; class Node { public:     int data;     Node* left;     Node* right;      Node(int x) {         data = x;         left = nullptr;         right = nullptr;     } };  // Recursive function used by leftMostShortest // to print the first shortest root to leaf path void printPath(int key, unordered_map<int, int>& parent) {          // If the root's data is same as its   	// parent data, return     if (parent[key] == key)          return;          // Recur for the function printPath     printPath(parent[key], parent);          // Print the parent node's data     cout << parent[key] << " "; }  // Function to perform level order traversal // until we find the first leaf node void leftMostShortest(Node* root) {      queue<Node*> q;     q.push(root);     int leafData = -1;          // To store the current node     Node* curr = nullptr;          // Map to store the parent node's data     unordered_map<int, int> parent;          // Parent of root data is set as its own value     parent[root->data] = root->data;          // Level-order traversal to find the   	// first leaf node     while (!q.empty()) {         curr = q.front();         q.pop();                  // If the current node is a leaf node         if (!curr->left && !curr->right) {             leafData = curr->data;             break;         }                  // Push the left child into the queue         if (curr->left) {             q.push(curr->left);             parent[curr->left->data] = curr->data;         }                  // Push the right child into the queue         if (curr->right) {             q.push(curr->right);             parent[curr->right->data] = curr->data;         }     }          printPath(leafData, parent);     cout << leafData << " "; }  int main() {        // Representation of the binary tree     //          1     //         / \     //        2   3     //       /      //      4       Node* root = new Node(1);     root->left = new Node(2);     root->right = new Node(3);     root->left->left = new Node(4);       leftMostShortest(root);      return 0; } 
Java
// Java program to print the first shortest // root to leaf path import java.util.*;  class Node {     int data;     Node left, right;      Node(int x) {         data = x;         left = null;         right = null;     } }  // Recursive function used by leftMostShortest // to print the first shortest root to leaf path class GfG {     static void printPath(int key,                     HashMap<Integer, Integer> parent) {                  // If the root's data is the same as          // its parent's data, return         if (parent.get(key) == key)              return;                  // Recur for the function printPath         printPath(parent.get(key), parent);                  // Print the parent node's data         System.out.print(parent.get(key) + " ");     }      // Function to perform level order traversal     // until we find the first leaf node     static void leftMostShortest(Node root) {                  Queue<Node> q = new LinkedList<>();         q.add(root);         int leafData = -1;                  // To store the current node         Node curr = null;                  // Map to store the parent node's data         HashMap<Integer, Integer> parent = new HashMap<>();                  // Parent of root data is set as its own value         parent.put(root.data, root.data);                  // Level-order traversal to find the       	// first leaf node         while (!q.isEmpty()) {             curr = q.poll();                          // If the current node is a leaf node             if (curr.left == null && curr.right == null) {                 leafData = curr.data;                 break;             }                          // Push the left child into the queue             if (curr.left != null) {                 q.add(curr.left);                 parent.put(curr.left.data, curr.data);             }                          // Push the right child into the queue             if (curr.right != null) {                 q.add(curr.right);                 parent.put(curr.right.data, curr.data);             }         }                  printPath(leafData, parent);                 System.out.print(leafData + " ");     }      public static void main(String[] args) {                  // Representation of the binary tree         //          1         //         / \         //        2   3         //       /            //      4             Node root = new Node(1);         root.left = new Node(2);         root.right = new Node(3);         root.left.left = new Node(4);          leftMostShortest(root);     } } 
Python
# Python program to print the first shortest # root to leaf path from collections import deque  class Node:     def __init__(self, x):         self.data = x         self.left = None         self.right = None  # Recursive function used by leftMostShortest # to print the first shortest root to leaf path def print_path(key, parent):          # If the root's data is the same as     # its parent data, return     if parent[key] == key:         return          # Recur for the function print_path     print_path(parent[key], parent)          # Print the parent node's data     print(parent[key], end=" ")  # Function to perform level order traversal # until we find the first leaf node def left_most_shortest(root):          # Queue to store the nodes     q = deque()          q.append(root)     leaf_data = -1      curr = None          # Dictionary to store the      # parent node's data     parent = {}          # Parent of root data is set as its own value     parent[root.data] = root.data          # Level-order traversal to find the      # first leaf node     while q:         curr = q.popleft()                  # If the current node is a leaf node         if not curr.left and not curr.right:             leaf_data = curr.data             break                  # Push the left child into the queue         if curr.left:             q.append(curr.left)             parent[curr.left.data] = curr.data                  # Push the right child into         # the queue         if curr.right:             q.append(curr.right)             parent[curr.right.data] = curr.data          print_path(leaf_data, parent)      print(leaf_data, end=" ")  if __name__ == "__main__":          # Representation of the binary tree     #          1     #         / \     #        2   3     #       /        #      4        root = Node(1)     root.left = Node(2)     root.right = Node(3)     root.left.left = Node(4)      left_most_shortest(root) 
C#
// C# program to print the first shortest // root to leaf path using System; using System.Collections.Generic;  class Node {     public int data;     public Node left, right;      public Node(int x) {         data = x;         left = null;         right = null;     } }  class GfG {        // Recursive function used by LeftMostShortest     // to print the first shortest root to leaf path     static void PrintPath(int key,                          Dictionary<int, int> parent) {                  // If the root's data is the same as          // its parent data, return         if (parent[key] == key)              return;                  // Recur for the function PrintPath         PrintPath(parent[key], parent);                  // Print the parent node's data         Console.Write(parent[key] + " ");     }      // Function to perform level order traversal     // until we find the first leaf node     static void LeftMostShortest(Node root) {                  Queue<Node> q = new Queue<Node>();         q.Enqueue(root);         int leafData = -1;                  // To store the current node         Node curr = null;                  // Dictionary to store the        	// parent node's data         Dictionary<int, int> parent                         = new Dictionary<int, int>();                  // Parent of root data is set as its own value         parent[root.data] = root.data;                  // Level-order traversal to find       	// the first leaf node         while (q.Count > 0) {             curr = q.Dequeue();                          // If the current node is a leaf node             if (curr.left == null && curr.right == null) {                 leafData = curr.data;                 break;             }                          // Push the left child into the queue             if (curr.left != null) {                 q.Enqueue(curr.left);                 parent[curr.left.data] = curr.data;             }                          // Push the right child into the queue             if (curr.right != null) {                 q.Enqueue(curr.right);                 parent[curr.right.data] = curr.data;             }         }                  PrintPath(leafData, parent);         Console.Write(leafData + " ");     }      static void Main(string[] args) {                  // Representation of the binary tree         //          1         //         / \         //        2   3         //       /            //      4             Node root = new Node(1);         root.left = new Node(2);         root.right = new Node(3);         root.left.left = new Node(4);          LeftMostShortest(root);     } } 
JavaScript
// JavaScript program to print the first shortest // root to leaf path class Node {     constructor(x) {         this.data = x;         this.left = null;         this.right = null;     } }  // Recursive function used by leftMostShortest // to print the first shortest root to leaf path function printPath(key, parent) {          // If the root's data is the same as     // its parent data, return     if (parent[key] === key)          return;          // Recur for the function printPath     printPath(parent[key], parent);          // Print the parent node's data     process.stdout.write(parent[key] + " "); }  // Function to perform level order traversal // until we find the first leaf node function leftMostShortest(root) {          let q = [];     q.push(root);      let leafData = -1;          // To store the current node     let curr = null;          // Map to store the parent node's data     let parent = {};          // Parent of root data is set as its own value     parent[root.data] = root.data;          // Level-order traversal to find the first leaf node     while (q.length > 0) {         curr = q.shift();                  // If the current node is a leaf node         if (!curr.left && !curr.right) {             leafData = curr.data;             break;         }                  // Push the left child into the queue         if (curr.left) {             q.push(curr.left);             parent[curr.left.data] = curr.data;         }                  // Push the right child into the queue         if (curr.right) {             q.push(curr.right);             parent[curr.right.data] = curr.data;         }     }      printPath(leafData, parent);     console.log(leafData + " "); }  // Representation of the binary tree //          1 //         / \ //        2   3 //       /   //      4    let root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4);  leftMostShortest(root); 

Output
1 3 

Time Complexity: O(n), where n is the number of nodes.
Auxiliary Space: O(n)



Next Article
Sort the path from root to a given node in a Binary Tree
author
sakshi_srivastava
Improve
Article Tags :
  • Data Structures
  • DSA
  • Hash
  • Tree
  • Binary Tree
  • tree-level-order
Practice Tags :
  • Data Structures
  • Hash
  • Tree

Similar Reads

  • Print Root-to-Leaf Paths in a Binary Tree
    Given a Binary Tree of nodes, the task is to find all the possible paths from the root node to all the leaf nodes of the binary tree. Example: Input: Output: 1 2 41 2 51 3 Using Recursion - O(n) Time and O(h) SpaceIn the recursive approach to print all paths from the root to leaf nodes, we can perfo
    2 min read
  • Sort the path from root to a given node in a Binary Tree
    Given a Binary tree, the task is to sort the particular path from to a given node of the binary tree. You are given a Key Node and Tree. The task is to sort the path till that particular node. Examples: Input : 3 / \ 4 5 / \ \ 1 2 6 key = 2 Output : 2 / \ 3 5 / \ \ 1 4 6 Inorder :- 1 3 4 2 5 6 Here
    6 min read
  • Find the maximum sum leaf to root path in a Binary Tree
    Given a Binary Tree, the task is to find the maximum sum path from a leaf to a root. Example : Input: Output: 60Explanantion: There are three leaf to root paths 20->30->10, 5->30->10 and 15->10. The sums of these three paths are 60, 45 and 25 respectively. The maximum of them is 60 an
    15+ min read
  • Print Root-to-Leaf Paths in a Binary Tree Using Recursion
    Given a Binary Tree of nodes, the task is to find all the possible paths from the root node to all the leaf nodes of the binary tree.Note: The paths should be returned such that paths from the left subtree of any node are listed first, followed by paths from the right subtree. Example: Input: root[]
    6 min read
  • Print the longest leaf to leaf path in a Binary tree
    C/C++ Code // C++ program to print the longest leaf to leaf // path #include <bits/stdc++.h> using namespace std; // Tree node structure used in the program struct Node { int data; Node *left, *right; }; struct Node* newNode(int data) { struct Node* node = new Node; node->data = data; node-
    15+ min read
  • Find all root to leaf path sum of a Binary Tree
    Given a Binary Tree, the task is to print all the root to leaf path sum of the given Binary Tree. Examples: Input: 30 / \ 10 50 / \ / \ 3 16 40 60 Output: 43 56 120 140 Explanation: In the above binary tree there are 4 leaf nodes. Hence, total 4 path sum are present from root node to the leaf node.
    8 min read
  • Print path from a node to root of given Complete Binary Tree
    Given an integer N, the task is to find the path from the Nth node to the root of a Binary Tree of the following form: The Binary Tree is a Complete Binary Tree up to the level of the Nth node.The nodes are numbered 1 to N, starting from the root as 1.The structure of the Tree is as follows: 1 / \ 2
    4 min read
  • Print all the paths from root, with a specified sum in Binary tree
    Given a Binary tree and a sum, the task is to return all the paths, starting from root, that sums upto the given sum.Note: This problem is different from root to leaf paths. Here path doesn't need to end on a leaf node. Examples: Input: Output: [[1, 3, 4]]Explanation: The below image shows the path
    8 min read
  • Print path from root to all nodes in a Complete Binary Tree
    Given a number N which is the total number of nodes in a complete binary tree where nodes are number from 1 to N sequentially level-wise. The task is to write a program to print paths from root to all of the nodes in the Complete Binary Tree.For N = 3, the tree will be: 1 / \ 2 3 For N = 7, the tree
    9 min read
  • Print all the root-to-leaf paths of a Binary Tree whose XOR is non-zero
    Given a Binary Tree, the task is to print all root-to-leaf paths of this tree whose xor value is non-zero. Examples: Input: 10 / \ 10 3 / \ 10 3 / \ / \ 7 3 42 13 / 7 Output: 10 3 10 7 10 3 3 42 Explanation: All the paths in the given binary tree are : {10, 10} xor value of the path is = 10 ^ 10 = 0
    11 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences