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:
Find if given vertical level of binary tree is sorted or not
Next article icon

Find Level wise positions of given node in a given Binary Tree

Last Updated : 01 Apr, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a binary tree and an integer X, the task is to find out all the occurrences of X in the given tree, and print its level and its position from left to right on that level. If X is not found, print -1.

Examples:

Input: X=35
              10
          /         \
     20          30
   /   \          /     \
40   60   35       50
Output: [(3, 3)]
Explanation: Integer X=35 is present in level 3 and its position is 3 from left.

Input: X= 2
                 1
            /         \
         2            3
      /   \         /     \
   4       6    8        2
Output: [(2, 1), (3, 4)]
Explanation: Integer X=2 is present in level 2 and its position is 1 from left also it is present in level 3 and position from left is 4.

 

Approach: This problem can be solved using level order traversal of binary tree using queue. 

  • Perform level order traversal of given Binary Tree using Queue.
  • Keep track of level count and the count of nodes from left to right during traversal
  • Whenever X is encountered during traversal, print or store the level count and position of current occurrence of X.

Below is the implementation of the above approach:

C++
// C++ program to print level and // position of Node X in binary tree  #include <bits/stdc++.h> using namespace std;  // A Binary Tree Node struct Node {     int data;     struct Node *left, *right; };  // Function to find and print // level and position of node X void printLevelandPosition(Node* root, int X) {     // Base Case     if (root == NULL)         return;      // Create an empty queue     queue<Node*> q;      // Enqueue Root and initialize height     q.push(root);      // Create and initialize current     // level and position by 1     int currLevel = 1, position = 1;      while (q.empty() == false) {          int size = q.size();          while (size--) {              Node* node = q.front();              // print if node data equal to X             if (node->data == X)                 cout << "(" << currLevel                      << " " << position                      << "), ";             q.pop();              // increment the position             position++;              // Enqueue left child             if (node->left != NULL)                 q.push(node->left);              // Enqueue right child             if (node->right != NULL)                 q.push(node->right);         }         // increment the level         currLevel++;         position = 1;     } }  // Utility function to create a new tree node Node* newNode(int data) {     Node* temp = new Node;     temp->data = data;     temp->left = temp->right = NULL;     return temp; }  // Driver program to test above functions int main() {     // Let us create binary tree     Node* root = newNode(1);     root->left = newNode(2);     root->right = newNode(3);     root->left->left = newNode(4);     root->left->right = newNode(2);      int X = 2;      printLevelandPosition(root, X);     return 0; } 
Java
// JAVA program to print level and // position of Node X in binary tree import java.util.*;  // A Binary Tree Node class Node {   int data;   Node left;   Node right; } class GFG {    // Function to find and print   // level and position of node X   public static void printLevelandPosition(Node root,                                            int X)   {     // Base Case     if (root == null)       return;      // Create an empty queue     Queue<Node> q = new LinkedList<>();      // Enqueue Root and initialize height     q.add(root);      // Create and initialize current     // level and position by 1     int currLevel = 1, position = 1;      while (q.size() != 0) {        int size = q.size();        while ((size--) != 0) {          Node node = q.peek();          // print if node data equal to X         if (node.data == X)           System.out.print("(" + currLevel + " "                            + position + "), ");         q.remove();          // increment the position         position++;          // Enqueue left child         if (node.left != null)           q.add(node.left);          // Enqueue right child         if (node.right != null)           q.add(node.right);       }       // increment the level       currLevel++;       position = 1;     }   }    // Utility function to create a new tree node   public static Node newNode(int data)   {     Node temp = new Node();     temp.data = data;     temp.left = temp.right = null;     return temp;   }    // Driver program to test above functions   public static void main(String[] args)   {     // Let us create binary tree     Node root = newNode(1);     root.left = newNode(2);     root.right = newNode(3);     root.left.left = newNode(4);     root.left.right = newNode(2);      int X = 2;      printLevelandPosition(root, X);   } }  // This code is contributed by Taranpreet 
Python3
# Python code for the above approach class Node:     def __init__(self,d):         self.data = d         self.left = None         self.right = None      # Function to find and print # level and position of node X def printLevelandPosition(root, X):       # Base Case     if (root == None):         return      # Create an empty queue     q = []      # Enqueue Root and initialize height     q.append(root)      # Create and initialize current     # level and position by 1     currLevel,position = 1,1      while (len(q) != 0):          size = len(q)          while (size != 0):              node = q[0]             q = q[1:]              # print if node data equal to X             if (node.data == X):                 print (f"({currLevel} {position}),",end =" ")                       # increment the position             position += 1              # Enqueue left child             if (node.left != None):                 q.append(node.left)              # Enqueue right child             if (node.right != None):                 q.append(node.right)                          size -= 1          # increment the level         currLevel += 1         position = 1  # Driver program to test above functions  # Let us create binary tree root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(2)  X = 2  printLevelandPosition(root, X)  # This code is contributed by shinjanpatra 
C#
// C# program to print level and // position of Node X in binary tree using System; using System.Collections.Generic;   // A Binary Tree Node public class Node {   public int data;   public Node left;   public Node right; }  public class GFG {    // Function to find and print   // level and position of node X   public static void printLevelandPosition(Node root, int X) {     // Base Case     if (root == null)       return;      // Create an empty queue     Queue<Node> q = new Queue<Node>();      // Enqueue Root and initialize height     q.Enqueue(root);      // Create and initialize current     // level and position by 1     int currLevel = 1, position = 1;      while (q.Count != 0) {        int size = q.Count;        while ((size--) != 0) {          Node node = q.Peek();          // print if node data equal to X         if (node.data == X)           Console.Write("(" + currLevel + " " + position + "), ");         q.Dequeue();          // increment the position         position++;          // Enqueue left child         if (node.left != null)           q.Enqueue(node.left);          // Enqueue right child         if (node.right != null)           q.Enqueue(node.right);       }       // increment the level       currLevel++;       position = 1;     }   }    // Utility function to create a new tree node   public static Node newNode(int data) {     Node temp = new Node();     temp.data = data;     temp.left = temp.right = null;     return temp;   }    // Driver program to test above functions   public static void Main(String[] args) {     // Let us create binary tree     Node root = newNode(1);     root.left = newNode(2);     root.right = newNode(3);     root.left.left = newNode(4);     root.left.right = newNode(2);      int X = 2;      printLevelandPosition(root, X);   } }  // This code is contributed by Rajput-Ji 
JavaScript
<script>         // JavaScript code for the above approach         class Node {             constructor(d) {                 this.data = d;                 this.left = null;                 this.right = null;             }         }          // Function to find and print         // level and position of node X         function printLevelandPosition(root, X)          {                      // Base Case             if (root == null)                 return;              // Create an empty queue             let q = [];              // Enqueue Root and initialize height             q.push(root);              // Create and initialize current             // level and position by 1             let currLevel = 1, position = 1;              while (q.length != 0) {                  let size = q.length;                  while (size-- != 0) {                      let node = q.shift();                      // print if node data equal to X                     if (node.data == X)                         document.write("(" + currLevel                             + " " + position                             + "), ");                       // increment the position                     position++;                      // Enqueue left child                     if (node.left != null)                         q.push(node.left);                      // Enqueue right child                     if (node.right != null)                         q.push(node.right);                 }                 // increment the level                 currLevel++;                 position = 1;             }         }          // Driver program to test above functions          // Let us create binary tree         let root = new Node(1);         root.left = new Node(2);         root.right = new Node(3);         root.left.left = new Node(4);         root.left.right = new Node(2);          let X = 2;          printLevelandPosition(root, X);         // This code is contributed by Potta Lokesh     </script> 

 
 


Output
(2 1), (3 2), 


 

Time Complexity: O(n) 
Auxiliary Space : O(n)


 


Next Article
Find if given vertical level of binary tree is sorted or not
author
nobita04
Improve
Article Tags :
  • Tree
  • Searching
  • Geeks Premier League
  • DSA
  • Geeks-Premier-League-2022
  • tree-level-order
Practice Tags :
  • Searching
  • Tree

Similar Reads

  • Find parent of given node in a Binary Tree with given postorder traversal
    Given two integers N and K where N denotes the height of a binary tree, the task is to find the parent of the node with value K in a binary tree whose postorder traversal is first [Tex]2^{N}-1 [/Tex] natural numbers [Tex](1, 2, ... 2^{N}-1) [/Tex] For N = 3, the Tree will be - 7 / \ 3 6 / \ / \ 1 2
    9 min read
  • Find if given vertical level of binary tree is sorted or not
    Given a binary tree. Find if a given vertical level of the binary tree is sorted or not. (For the case when two nodes are overlapping, check if they form a sorted sequence in the level they lie.)Prerequisite: Vertical Order Traversal Examples: Input : 1 / \ 2 5 / \ 7 4 / 6 Level l = -1 Output : YesN
    13 min read
  • Print cousins of a given node in Binary Tree
    Given a binary tree and a node, print all cousins of given node. Note that siblings should not be printed.Example: Input : root of below tree 1 / \ 2 3 / \ / \ 4 5 6 7 and pointer to a node say 5. Output : 6, 7 The idea to first find level of given node using the approach discussed here. Once we hav
    15+ min read
  • Find sum of all left leaves in a given Binary Tree
    Given a Binary Tree, find the sum of all left leaves in it. For example, sum of all left leaves in below Binary Tree is 5+1=6. Recommended PracticeSum of Left Leaf NodesTry It! The idea is to traverse the tree, starting from root. For every node, check if its left subtree is a leaf. If it is, then a
    15+ min read
  • Print even positioned nodes of even levels in level order of the given binary tree
    Given a binary tree, print even positioned nodes of even level in level order traversal. The root is considered at level 0, and the left most node of any level is considered as a node at position 0. Examples: Input: 1 / \ 2 3 / \ \ 4 5 6 / \ 7 8 / \ 9 10 Output: 1 4 6 9 Input: 2 / \ 4 15 / / 45 17 O
    8 min read
  • Check if a binary tree is sorted level-wise or not
    Given a binary tree. The task is to check if the binary tree is sorted level-wise or not. A binary tree is level sorted if max( i-1th level) is less than min( ith level ). Examples: Input : 1 / \ / \ 2 3 / \ / \ / \ / \ 4 5 6 7 Output : Sorted Input: 1 / 4 / \ 6 5 \ 2 Output: Not sorted Simple Solut
    10 min read
  • Closest leaf to a given node in Binary Tree
    Given a Binary Tree and a node x in it, find distance of the closest leaf to x in Binary Tree. If given node itself is a leaf, then distance is 0.Examples: Input: Root of below tree And x = pointer to node 13 10 / \ 12 13 / 14 Output 1 Distance 1. Closest leaf is 14. Input: Root of below tree And x
    12 min read
  • Count levels in a Binary Tree consisting of node values having set bits at different positions
    Given a Binary Tree consisting of N nodes, the task is to count the number of levels in a Binary Tree such that the set bits of all the node values at the same level is at different positions. Examples: Input: 5 / \ 6 9 / \ \ 1 4 7 Output: 2 Explanation: Level 1 has only 5 (= (101)2). Level 2 has 6
    10 min read
  • Print all nodes between two given levels in Binary Tree
    Given a binary tree, the task is to print all nodes between two given levels in a binary tree. Print the nodes level-wise, i.e., the nodes for any level should be printed from left to right. Note: The levels are 1-indexed, i.e., root node is at level 1. Example: Input: Binary tree, l = 2, h = 3 Outp
    8 min read
  • Find distance from root to given node in a binary tree
    Given the root of a binary tree and a key x in it, find the distance of the given key from the root. Dis­tance means the num­ber of edges between two nodes. Examples: Input: x = 45 Output: 3 Explanation: There are three edges on path from root to 45.For more understanding of question, in above tree
    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