VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-value-k-in-given-complete-binary-tree-with-values-indexed-from-1-to-n/

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


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 12 Jul, 2025

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: 


Output: 
true

 

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

Comment
Article Tags: