Question

C++ implementation Return the number of nodes in a binary search tree that are greater than...

C++ implementation

Return the number of nodes in a binary search tree that are greater than the amount that the user enters.

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

#include <bits/stdc++.h>

using namespace std;

struct Node

{

int data;

vector<Node*> child;

};

Node* newNode(int data)

{

Node* temp = new Node;

temp->data = data;

return temp;

}

int nodesGreater(Node* root, int search)

{

if (root == NULL)

return 0;

int count = 0;

if(root->data > search)

count++;

int numNodes = root->child.size();

for (int i = 0; i < numNodes; i++)

{

Node* child = root->child[i];

count += nodesGreater(child, search);

}

return count;

}

int main()

{

Node* root = newNode(5);

(root->child).push_back(newNode(6));

(root->child).push_back(newNode(3));

(root->child).push_back(newNode(4));

(root->child[0]->child).push_back(newNode(22));

(root->child[1]->child).push_back(newNode(17));

(root->child[1]->child).push_back(newNode(9));

(root->child[2]->child).push_back(newNode(8));

cout << "\nDemo Binary search tree has been constructed." << endl;

int search;

cout << "Please enter an integer to search: ";

cin >> search;

int nNodesGreater = nodesGreater(root, search);

if(nNodesGreater == 0)

cout << "Sorry, there are no nodes greater than " << search << endl;

else

cout << "Number of nodes greater than " << search << " are = " << nNodesGreater << endl;

return 0;

}

********************************************************** SCREENSHOT ******************************************************

saved main.cpp 3 TELUI Cuir, 31 } clang version 7.0.0-3-ubuntu0.18.04.1 (tags/RELEASE 700/final clang++-7 -pthread -o main ma

Add a comment
Know the answer?
Add Answer to:
C++ implementation Return the number of nodes in a binary search tree that are greater than...
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
ADVERTISEMENT