Question

Write a function int levelSearch(Node* root, int key) in c++ that takes as input the root...

Write a function int levelSearch(Node* root, int key) in c++ that takes as input the root node of a Binary Search tree and a key. The function searches the key in the BST and returns the level of the found node. If the key is not found in the tree, return -1. The level starts at 1 for the root node and increases from top to bottom.

We have defined the following node C++ Node class for you:

class Node {
    public:
        int name;
        Node* left = NULL;
        Node* right = NULL;
};

Note: In the test cases, the first line for input has multiple nodes and we will be inserting each one of them in your tree using an insert function. The second line is the key to be searched. The output is the level of the key in the BST.

Sample Input 1:

8 11 15 2 5 
5

Sample Output 1:

3

Sample Input 2:

8 11 15 2 5 
8

Sample Output 2:

1
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Given below the needed code. Please do rate the answer if it helped. In case of any issues, post a comment.

int levelSearch(Node* root, int key){
   int level = 1;
   Node* n = root;
   while(n != NULL){
       if(n->name == key)
           return level;
       else if(key < n->name)
           n = n->left;
       else
           n = n->right;
       level++;
   }
  
   return -1; //not found
}

Add a comment
Know the answer?
Add Answer to:
Write a function int levelSearch(Node* root, int key) in c++ that takes as input the root...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT