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 distance from root to given node in a binary tree
Next article icon

Find value K in given Complete Binary Tree with values indexed from 1 to N

Last Updated : 27 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a complete binary tree with values indexed from 1 to N and a key K. The task is to check whether a key exists in the tree or not. Print "true" if the key exists, otherwise print "false". 

Complete Binary Tree: A Binary Tree is a complete Binary Tree if all the levels are completely filled except possibly the last level and the last level has all keys as left as possible 

Examples: 


Input: K = 2 

         1        /   \        2      3       /  \   / \    4    5 6   7  /  \   / 8    9 10

Output: true 
 

Input: K = 11 

         1        /   \        2      3       /  \   / \    4    5 6   7  /  \   / 8    9 10


Output: false 

Naive Approach: The simplest approach would be to simply traverse the entire tree and check if the key exists in the tree or not.

Time Complexity: O(N) 
Auxiliary Space: O(1)

Efficient Approach: The approach is based on the idea that the tree is a complete binary tree and the nodes are indexed from 1 to N starting from the top. So we can track down the path going from the root to the key if at all the key existed. Below are the steps:

  1. For a complete binary tree given node i, its children will be 2*i and 2*i + 1. Therefore, given node i, its parent node will be i/2.
  2. Iteratively find out the parent of the key until the root node of the tree is found, and store the steps in an array steps[] as -1 for left and 1 for right (Left means that the current node is the left child of its parent and right means the current node is the right child of its parent).
  3. Now transverse the tree according to the moves stored in the array steps[]. If the entire array is successfully transversed, it means that the key exists in the tree so print "True", otherwise print "False".

 Below is the implementation of the above approach: 

C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std;  // Class containing left // and right child of current node // and key value class Node {   public:     int data;     Node* left;     Node* right;       Node(int item)     {         data = item;         left = NULL;         right = NULL;     } };  // Function to store the // list of the directions vector<int> findSteps(Node* root, int data) {     vector<int> steps;          // While the root is not found     while (data != 1) {         // If it is the right         // child of its parent         if (data / 2.0 > data / 2) {              // Add right step (1)             steps.push_back(1);         }         else {              // Add left step (-1)             steps.push_back(-1);         }          int parent = data / 2;          // Repeat the same         // for its parent         data = parent;     }      // Reverse the steps list     reverse(steps.begin(), steps.end());      // Return the steps     return steps; }  // Function to find // if the key is present or not bool findKey(Node* root, int data) {     // Get the steps to be followed     vector<int> steps = findSteps(root, data);          // Taking one step at a time     for (auto cur_step : steps)      {             // Go left             if (cur_step == -1) {                   // If left child does                 // not exist return false                 if (root->left == NULL)                     return false;                   root = root->left;             }                          // Go right             else {                   // If right child does                 // not exist return false                 if (root->right == NULL)                     return false;                   root = root->right;             }         }           // If the entire array of steps         // has been successfully         // traversed         return true; }    int main() {     /* Consider the following complete binary tree                  1                 / \                 2   3                / \ / \              4  5 6  7             / \ /            8  9 10      */     Node* 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(5);     root->right->left = new Node(6);     root->right->right = new Node(7);     root->left->left->left = new Node(8);     root->left->left->right = new Node(9);     root->left->right->left = new Node(10);          // Function Call     cout<<boolalpha<<findKey(root, 7)<<endl; }  // This code is contributed by Pushpesh Raj. 
Java
// Java program for the above approach import java.util.*; import java.io.*;  // Class containing left // and right child of current node // and key value class Node {     int data;     Node left, right;      public Node(int item)     {         data = item;         left = null;         right = null;     } }  class Solution {      // Function to store the     // list of the directions     public static ArrayList<Integer>     findSteps(Node root, int data)     {         ArrayList<Integer> steps             = new ArrayList<Integer>();          // While the root is not found         while (data != 1) {             // If it is the right             // child of its parent             if (data / 2.0 > data / 2) {                  // Add right step (1)                 steps.add(1);             }             else {                  // Add left step (-1)                 steps.add(-1);             }              int parent = data / 2;              // Repeat the same             // for its parent             data = parent;         }          // Reverse the steps list         Collections.reverse(steps);          // Return the steps         return steps;     }      // Function to find     // if the key is present or not     public static boolean     findKey(Node root, int data)     {         // Get the steps to be followed         ArrayList<Integer> steps             = findSteps(root, data);          // Taking one step at a time         for (Integer cur_step : steps) {              // Go left             if (cur_step == -1) {                  // If left child does                 // not exist return false                 if (root.left == null)                     return false;                  root = root.left;             }              // Go right             else {                  // If right child does                 // not exist return false                 if (root.right == null)                     return false;                  root = root.right;             }         }          // If the entire array of steps         // has been successfully         // traversed         return true;     }      public static void main(String[] args)     {         /* Consider the following complete binary tree                   1                  / \                  2   3                 / \ / \               4  5 6  7              / \ /             8  9 10           */         Node 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(5);         root.right.left = new Node(6);         root.right.right = new Node(7);         root.left.left.left = new Node(8);         root.left.left.right = new Node(9);         root.left.right.left = new Node(10);          // Function Call         System.out.println(findKey(root, 7));     } } 
Python3
# Python program to implement above approach  # Class containing left # and right child of current node # and key value class Node:     def __init__(self,item):              self.data = item         self.left = None         self.right = None       # Function to store the # list of the directions  def findSteps(root,data):     steps = []      # While the root is not found     while (data != 1):              # If it is the right         # child of its parent         if (data / 2 > data // 2):              # Add right step (1)             steps.append(1)         else:              # Add left step (-1)             steps.append(-1)          parent = data // 2          # Repeat the same         # for its parent         data = parent      # Reverse the steps list     steps = steps[::-1]      # Return the steps     return steps  # Function to find # if the key is present or not  def findKey(root,data):      # Get the steps to be followed     steps = findSteps(root, data)      # Taking one step at a time     for cur_step in steps:          # Go left         if (cur_step == -1):              # If left child does             # not exist return False             if (root.left == None):                 return False              root = root.left          # Go right         else:              # If right child does             # not exist return False             if (root.right == None):                 return False              root = root.right      # If the entire array of steps     # has been successfully     # traversed     return True  # driver code  #  Consider the following complete binary tree #                 1 #                 / \ #             2 3 #             / \ / \ #             4 5 6 7 #             / \ / #         8 9 10 #          root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.left = Node(6) root.right.right = Node(7) root.left.left.left = Node(8) root.left.left.right = Node(9) root.left.right.left = Node(10)  # Function Call print(findKey(root, 7))  # This code is contributed by shinjanpatra 
C#
// C# program for the above approach using System; using System.Collections.Generic;  // Class containing left // and right child of current node // and key value class Node {     public int data;     public Node left, right;       public Node(int item)     {         data = item;         left = right = null;     } }  class Solution {      // Function to store the     // list of the directions     public static List<int>     findSteps(Node root, int data)     {         List<int> steps             = new List<int>();          // While the root is not found         while (data != 1) {             // If it is the right             // child of its parent             if (data / 2.0 > data / 2) {                  // Add right step (1)                 steps.Add(1);             }             else {                  // Add left step (-1)                 steps.Add(-1);             }              int parent = data / 2;              // Repeat the same             // for its parent             data = parent;         }          // Reverse the steps list         steps.Reverse();          // Return the steps         return steps;     }      // Function to find     // if the key is present or not     public static bool     findKey(Node root, int data)     {         // Get the steps to be followed         List<int> steps             = findSteps(root, data);          // Taking one step at a time         foreach (int cur_step in steps) {              // Go left             if (cur_step == -1) {                  // If left child does                 // not exist return false                 if (root.left == null)                     return false;                  root = root.left;             }              // Go right             else {                  // If right child does                 // not exist return false                 if (root.right == null)                     return false;                  root = root.right;             }         }          // If the entire array of steps         // has been successfully         // traversed         return true;     }      public static void Main()     {         /* Consider the following complete binary tree                   1                  / \                  2   3                 / \ / \               4  5 6  7              / \ /             8  9 10           */         Node 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(5);         root.right.left = new Node(6);         root.right.right = new Node(7);         root.left.left.left = new Node(8);         root.left.left.right = new Node(9);         root.left.right.left = new Node(10);          // Function Call         Console.Write(findKey(root, 7));     } } 
JavaScript
<script>  // JavaScript program to implement above approach  // Class containing left // and right child of current node // and key value class Node {     constructor(item)     {         this.data = item;         this.left = null;         this.right = null;     } }  // Function to store the // list of the directions  function findSteps(root,data) {     let steps = [];      // While the root is not found     while (data != 1)     {              // If it is the right         // child of its parent         if (data / 2 > Math.floor(data / 2)) {              // Add right step (1)             steps.push(1);         }         else {              // Add left step (-1)             steps.push(-1);         }          let parent = Math.floor(data / 2);          // Repeat the same         // for its parent         data = parent;     }      // Reverse the steps list     steps.reverse();      // Return the steps     return steps; }  // Function to find // if the key is present or not  function findKey(root,data) {         // Get the steps to be followed     let steps = findSteps(root, data);      // Taking one step at a time     for (let cur_step of steps) {          // Go left         if (cur_step == -1) {              // If left child does             // not exist return false             if (root.left == null)                 return false;              root = root.left;         }          // Go right         else {              // If right child does             // not exist return false             if (root.right == null)                 return false;              root = root.right;         }     }      // If the entire array of steps     // has been successfully     // traversed     return true; }  // driver code  /* Consider the following complete binary tree                 1                 / \             2 3             / \ / \             4 5 6 7             / \ /         8 9 10         */ 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(5); root.right.left = new Node(6); root.right.right = new Node(7); root.left.left.left = new Node(8); root.left.left.right = new Node(9); root.left.right.left = new Node(10);  // Function Call document.write(findKey(root, 7),"</br>");  // This code is contributed by shinjanpatra  </script> 

Output: 
true

 

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


Next Article
Find distance from root to given node in a binary tree

A

Anannya Uberoi 1
Improve
Article Tags :
  • Tree
  • Algorithms
  • Searching
  • Data Structures
  • DSA
  • Google
  • Complete Binary Tree
Practice Tags :
  • Google
  • Algorithms
  • Data Structures
  • Searching
  • Tree

Similar Reads

  • 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
  • Find the largest Complete Subtree in a given Binary Tree
    Given a Binary Tree, the task is to find the size and also the inorder traversal of the largest Complete sub-tree in the given Binary Tree. Complete Binary Tree - A Binary tree is a Complete Binary Tree if all levels are filled except possibly the last level and the last level has all keys as left a
    13 min read
  • Distance between two nodes of binary tree with node values from 1 to N
    Given a binary tree with 1 as its root and for any parent i its left child will be 2*i and right child will be 2*i+1. The task is to find the minimum distance between two nodes n1 and n2. 1 / \ 2 3 / \ / \ 4 5 6 7 / \ / \ / \ / \ . . . . . . . . Examples: Input : n1 = 7, n2 = 10 Output : 5 Input : n
    7 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
  • 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
  • Count the number of paths from root to leaf of a Binary tree with given XOR value
    Given a value K and a binary tree, we have to find out the total number of paths from the root to leaf nodes having XOR of all its nodes along the path equal to K.Examples: Input: K = 6 2 / \ 1 4 / \ 10 5 Output: 2 Explanation: Subtree 1: 2 \ 4 This particular path has 2 nodes, 2 and 4 and (2 xor 4)
    8 min read
  • Find K smallest leaf nodes from a given Binary Tree
    Given a binary tree and an integer K, the task is to find the K smallest leaf nodes from the given binary tree. The number of leaf nodes will always be at least K. Examples: Input: 1 / \ 2 3 / \ / \ 4 5 6 7 / \ \ 21 8 19Output: 6 8 19Explanation:There are 4 leaf nodes in the above binary tree out of
    7 min read
  • Find the level with maximum setbit count in given Binary Tree
    Given a binary tree having N nodes, the task is to find the level having the maximum number of setbits. Note: If two levels have same number of setbits print the one which has less no of nodes. If nodes are equal print the first level from top to bottom Examples: Input: 2 / \ 5 3 / \6 1Output: 2Expl
    11 min read
  • Diameter of a Binary Indexed Tree with N nodes
    Given a Binary Indexed Tree with N nodes except root node 0 (Numbered from 1 to N), Find its diameter. Binary Indexed Tree is a tree where parent of a node number X = X - (X & (X - 1)) i.e. last bit is unset in X. The diameter of a tree is the longest simple path between any two leaves. Examples
    7 min read
  • Sum of all nodes with smaller values at a distance K from a given node in a BST
    Given a Binary Search Tree, a target node in the BST, and an integer value K, the task is to find the sum of all nodes that are at a distance K from the target node whose value is less than the target node. Examples: Input: target = 7, K = 2 Output: 11Explanation:The nodes at a distance K(= 2) from
    15+ 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