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:
Check whether an undirected graph contains cycle or not
Next article icon

Check whether a node is leaf node or not for multiple queries

Last Updated : 13 Aug, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a tree with N vertices numbered from 0 to N – 1 where 0 is the root node. The task is to check if a node is leaf node or not for multiple queries.
Examples: 
 

Input:        0      /   \    1      2  /  \ 3    4      /   5 q[] = {0, 3, 4, 5} Output: No Yes No Yes From the graph, 2, 3 and 5 are the only leaf nodes.


 


Approach: Store the degree of all the vertices in an array degree[]. For each edge from A to B, degree[A] and degree[B] are incremented by 1. Now every node which not a root node and it has a degree of 1 is a leaf node and all the other nodes are not.
Below is the implementation of the above approach: 
 

C++
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std;  // Function to calculate the degree of all the vertices void init(int degree[], vector<pair<int, int> > edges, int n) {     // Initializing degree of all the vertices as 0     for (int i = 0; i < n; i++) {         degree[i] = 0;     }      // For each edge from A to B, degree[A] and degree[B]     // are increased by 1     for (int i = 0; i < edges.size(); i++) {         degree[edges[i].first]++;         degree[edges[i].second]++;     } }  // Function to perform the queries void performQueries(vector<pair<int, int> > edges,                     vector<int> q, int n) {     // To store the of degree     // of all the vertices     int degree[n];      // Calculate the degree for all the vertices     init(degree, edges, n);      // For every query     for (int i = 0; i < q.size(); i++) {          int node = q[i];         if (node == 0) {             cout << "No\n";             continue;         }         // If the current node has 1 degree         if (degree[node] == 1)             cout << "Yes\n";         else             cout << "No\n";     } }  // Driver code int main() {      // Number of vertices     int n = 6;      // Edges of the tree     vector<pair<int, int> > edges = {         { 0, 1 }, { 0, 2 }, { 1, 3 }, { 1, 4 }, { 4, 5 }     };      // Queries     vector<int> q = { 0, 3, 4, 5 };      // Perform the queries     performQueries(edges, q, n);      return 0; } 
Java
// Java implementation of the approach import java.util.*;  class GFG  { static class pair {      int first, second;      public pair(int first, int second)      {          this.first = first;          this.second = second;      }  }   // Function to calculate the degree  // of all the vertices static void init(int degree[],                      pair[] edges, int n) {     // Initializing degree of      // all the vertices as 0     for (int i = 0; i < n; i++)      {         degree[i] = 0;     }      // For each edge from A to B,      // degree[A] and degree[B]     // are increased by 1     for (int i = 0; i < edges.length; i++)      {         degree[edges[i].first]++;         degree[edges[i].second]++;     } }  // Function to perform the queries static void performQueries(pair [] edges,                            int []q, int n) {     // To store the of degree     // of all the vertices     int []degree = new int[n];      // Calculate the degree for all the vertices     init(degree, edges, n);      // For every query     for (int i = 0; i < q.length; i++)     {          int node = q[i];         if (node == 0)         {             System.out.println("No");             continue;         }                  // If the current node has 1 degree         if (degree[node] == 1)             System.out.println("Yes");         else             System.out.println("No");     } }  // Driver code public static void main(String[] args) {     // Number of vertices     int n = 6;      // Edges of the tree     pair[] edges = {new pair(0, 1),                      new pair(0, 2),                     new pair(1, 3),                      new pair(1, 4),                      new pair(4, 5)};      // Queries     int []q = { 0, 3, 4, 5 };      // Perform the queries     performQueries(edges, q, n); } }  // This code is contributed by Rajput-Ji 
Python3
# Python3 implementation of the approach   # Function to calculate the degree # of all the vertices  def init(degree, edges, n) :       # Initializing degree of     # all the vertices as 0      for i in range(n) :         degree[i] = 0;       # For each edge from A to B,      # degree[A] and degree[B]      # are increased by 1      for i in range(len(edges)) :         degree[edges[i][0]] += 1;          degree[edges[i][1]] += 1;   # Function to perform the queries  def performQueries(edges, q, n) :       # To store the of degree      # of all the vertices      degree = [0] * n;       # Calculate the degree for all the vertices      init(degree, edges, n);       # For every query      for i in range(len(q)) :          node = q[i];          if (node == 0) :             print("No");              continue;           # If the current node has 1 degree          if (degree[node] == 1) :             print("Yes");          else :             print("No");   # Driver code  if __name__ == "__main__" :       # Number of vertices      n = 6;       # Edges of the tree      edges = [[ 0, 1 ], [ 0, 2 ],               [ 1, 3 ], [ 1, 4 ],               [ 4, 5 ]];       # Queries      q = [ 0, 3, 4, 5 ];       # Perform the queries      performQueries(edges, q, n);   # This code is contributed by AnkitRai01 
C#
// C# implementation of the approach using System;                      class GFG  { public class pair {      public int first, second;      public pair(int first, int second)      {          this.first = first;          this.second = second;      }  }   // Function to calculate the degree  // of all the vertices static void init(int []degree,                  pair[] edges, int n) {     // Initializing degree of      // all the vertices as 0     for (int i = 0; i < n; i++)      {         degree[i] = 0;     }      // For each edge from A to B,      // degree[A] and degree[B]     // are increased by 1     for (int i = 0; i < edges.Length; i++)      {         degree[edges[i].first]++;         degree[edges[i].second]++;     } }  // Function to perform the queries static void performQueries(pair [] edges,                             int []q, int n) {     // To store the of degree     // of all the vertices     int []degree = new int[n];      // Calculate the degree for all the vertices     init(degree, edges, n);      // For every query     for (int i = 0; i < q.Length; i++)     {          int node = q[i];         if (node == 0)         {             Console.WriteLine("No");             continue;         }                  // If the current node has 1 degree         if (degree[node] == 1)             Console.WriteLine("Yes");         else             Console.WriteLine("No");     } }  // Driver code public static void Main(String[] args) {     // Number of vertices     int n = 6;      // Edges of the tree     pair[] edges = {new pair(0, 1),                      new pair(0, 2),                     new pair(1, 3),                      new pair(1, 4),                      new pair(4, 5)};      // Queries     int []q = { 0, 3, 4, 5 };      // Perform the queries     performQueries(edges, q, n); } }  // This code is contributed by 29AjayKumar 
JavaScript
<script>  // JavaScript implementation of the approach  // Function to calculate the degree of all the vertices function init(degree, edges, n) {     // Initializing degree of all the vertices as 0     for (var i = 0; i < n; i++) {         degree[i] = 0;     }      // For each edge from A to B, degree[A] and degree[B]     // are increased by 1     for (var i = 0; i < edges.length; i++) {         degree[edges[i][0]]++;         degree[edges[i][1]]++;     } }  // Function to perform the queries function performQueries( edges, q, n) {     // To store the of degree     // of all the vertices     var degree = Array(n);      // Calculate the degree for all the vertices     init(degree, edges, n);      // For every query     for (var i = 0; i < q.length; i++) {          var node = q[i];         if (node == 0) {             document.write( "No<br>");             continue;         }         // If the current node has 1 degree         if (degree[node] == 1)             document.write( "Yes<br>");         else             document.write( "No<br>");     } }  // Driver code // Number of vertices var n = 6; // Edges of the tree var edges = [     [ 0, 1 ], [ 0, 2 ], [ 1, 3 ], [ 1, 4 ], [ 4, 5 ] ]; // Queries var q = [ 0, 3, 4, 5 ]; // Perform the queries performQueries(edges, q, n);  </script>   

Output: 
No Yes No Yes

 

Time complexity: O(n)
Auxiliary Space: O(n). 
 


Next Article
Check whether an undirected graph contains cycle or not

P

Pratims10
Improve
Article Tags :
  • Tree
  • Technical Scripter
  • Competitive Programming
  • Data Structures
  • DSA
  • Arrays
Practice Tags :
  • Arrays
  • Data Structures
  • Tree

Similar Reads

  • Find parent of each node in a tree for multiple queries
    Given a tree with N vertices numbered from 0 to N – 1 and Q query containing nodes in the tree, the task is to find the parent node of the given node for multiple queries. Consider the 0th node as the root node and take the parent of the root node as the root itself.Examples: Tree: 0 / \ 1 2 | / \ 3
    8 min read
  • Check if a node is an Internal Node or not
    Given a binary tree, for each node check whether it is an internal node or not. Examples: Input: Output: Node A: TrueNode B: TrueNode C: FalseNode D: FalseExplanation: In this illustration, Node A possesses two child nodes (B and C) which categorizes it as a node. On the other hand, both Nodes B pos
    4 min read
  • Check whether BST contains Dead End or not
    Given a Binary search Tree that contains positive integer values greater than 0. The task is to check whether the BST contains a dead end or not. Here Dead End means, we are not able to insert any element after that node. Examples: Input : 8 / \ 5 9 / \ 2 7 / 1 Output : YesExplanation : Node "1" is
    15+ min read
  • Check whether an undirected graph contains cycle or not
    Given an undirected graph, the task is to check whether it has a cycle or not, and if it has a cycle return the vertices of the cycle. Examples: Input: Output: Cycle exists. 3 -> 2 -> 1Explanation: Cycle exists for 3 -> 2 ->1 Input: Output: Cycle does not exist. Approach: This problem ca
    15 min read
  • Check whether given degrees of vertices represent a Graph or Tree
    Given the number of vertices and the degree of each vertex where vertex numbers are 1, 2, 3,...n. The task is to identify whether it is a graph or a tree. It may be assumed that the graph is Connected. Examples: Input : 5 2 3 1 1 1 Output : Tree Explanation : The input array indicates that vertex on
    5 min read
  • Check if two nodes are in same subtree of the root node
    Given a Binary Tree with distinct nodes. Given two nodes node1 and node2, check if the two nodes lies in the same subtree of the root node. That is, either of the left and right subtrees of the root node. For Example: In the above binary tree, node 3 and 8 are in the same subtree but 4 and 5 are in
    9 min read
  • Find the number of colored nodes according to given queries in a full Binary Tree
    Consider a full Binary Tree where the root of the Tree is colored as Black initially. Each black-colored node will have red children, and red-colored nodes will have black children. You are given two integer arrays Start[] and End[]. Along with Start[] and End[], there is a Query[] array of size Q w
    11 min read
  • Check whether a given Binary Tree is Complete or not (Iterative Solution)
    Given a Binary Tree, the task is to check whether the given Binary Tree is a Complete Binary Tree or not.A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible. Examples: The following trees are examples
    12 min read
  • Check Whether a Linked List is Bipartite or Not
    Given a linked list representing a graph with directed edges, check whether the given linked list is a Bipartite graph or not. Examples: Input: 1->2->3->4->NULLOutput: PossibleExplanation: It is possible to color the above linked list using 2 colors. We can color node 1 and 3 with one co
    8 min read
  • Number of leaf nodes in the subtree of every node of an n-ary tree
    Given an N-ary tree, print the number of leaf nodes in the subtree of every node. Examples: Input: 1 / \ 2 3 / | \ 4 5 6 Output: The node 1 has 4 leaf nodes The node 2 has 1 leaf nodes The node 3 has 3 leaf nodes The node 4 has 1 leaf nodes The node 5 has 1 leaf nodes The node 6 has 1 leaf nodes App
    8 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