Find value K in given Complete Binary Tree with values indexed from 1 to N
Last Updated :
27 Mar, 2023
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:
- 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.
- 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).
- 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++
#include <bits/stdc++.h>
using namespace std;
class Node {
public :
int data;
Node* left;
Node* right;
Node( int item)
{
data = item;
left = NULL;
right = NULL;
}
};
vector< int > findSteps(Node* root, int data)
{
vector< int > steps;
while (data != 1) {
if (data / 2.0 > data / 2) {
steps.push_back(1);
}
else {
steps.push_back(-1);
}
int parent = data / 2;
data = parent;
}
reverse(steps.begin(), steps.end());
return steps;
}
bool findKey(Node* root, int data)
{
vector< int > steps = findSteps(root, data);
for ( auto cur_step : steps)
{
if (cur_step == -1) {
if (root->left == NULL)
return false ;
root = root->left;
}
else {
if (root->right == NULL)
return false ;
root = root->right;
}
}
return true ;
}
int main()
{
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);
cout<<boolalpha<<findKey(root, 7)<<endl;
}
|
Java
import java.util.*;
import java.io.*;
class Node {
int data;
Node left, right;
public Node( int item)
{
data = item;
left = null ;
right = null ;
}
}
class Solution {
public static ArrayList<Integer>
findSteps(Node root, int data)
{
ArrayList<Integer> steps
= new ArrayList<Integer>();
while (data != 1 ) {
if (data / 2.0 > data / 2 ) {
steps.add( 1 );
}
else {
steps.add(- 1 );
}
int parent = data / 2 ;
data = parent;
}
Collections.reverse(steps);
return steps;
}
public static boolean
findKey(Node root, int data)
{
ArrayList<Integer> steps
= findSteps(root, data);
for (Integer cur_step : steps) {
if (cur_step == - 1 ) {
if (root.left == null )
return false ;
root = root.left;
}
else {
if (root.right == null )
return false ;
root = root.right;
}
}
return true ;
}
public static void main(String[] args)
{
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 );
System.out.println(findKey(root, 7 ));
}
}
|
Python3
class Node:
def __init__( self ,item):
self .data = item
self .left = None
self .right = None
def findSteps(root,data):
steps = []
while (data ! = 1 ):
if (data / 2 > data / / 2 ):
steps.append( 1 )
else :
steps.append( - 1 )
parent = data / / 2
data = parent
steps = steps[:: - 1 ]
return steps
def findKey(root,data):
steps = findSteps(root, data)
for cur_step in steps:
if (cur_step = = - 1 ):
if (root.left = = None ):
return False
root = root.left
else :
if (root.right = = None ):
return False
root = root.right
return True
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 )
print (findKey(root, 7 ))
|
C#
using System;
using System.Collections.Generic;
class Node
{
public int data;
public Node left, right;
public Node( int item)
{
data = item;
left = right = null ;
}
}
class Solution {
public static List< int >
findSteps(Node root, int data)
{
List< int > steps
= new List< int >();
while (data != 1) {
if (data / 2.0 > data / 2) {
steps.Add(1);
}
else {
steps.Add(-1);
}
int parent = data / 2;
data = parent;
}
steps.Reverse();
return steps;
}
public static bool
findKey(Node root, int data)
{
List< int > steps
= findSteps(root, data);
foreach ( int cur_step in steps) {
if (cur_step == -1) {
if (root.left == null )
return false ;
root = root.left;
}
else {
if (root.right == null )
return false ;
root = root.right;
}
}
return true ;
}
public static void Main()
{
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);
Console.Write(findKey(root, 7));
}
}
|
Javascript
<script>
class Node {
constructor(item)
{
this .data = item;
this .left = null ;
this .right = null ;
}
}
function findSteps(root,data)
{
let steps = [];
while (data != 1)
{
if (data / 2 > Math.floor(data / 2)) {
steps.push(1);
}
else {
steps.push(-1);
}
let parent = Math.floor(data / 2);
data = parent;
}
steps.reverse();
return steps;
}
function findKey(root,data)
{
let steps = findSteps(root, data);
for (let cur_step of steps) {
if (cur_step == -1) {
if (root.left == null )
return false ;
root = root.left;
}
else {
if (root.right == null )
return false ;
root = root.right;
}
}
return true ;
}
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);
document.write(findKey(root, 7), "</br>" );
</script>
|
Time Complexity: O(logN)
Auxiliary Space: O(logN)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...