Number of nodes greater than a given value in n-ary tree in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that counts the number of nodes whose value is greater than the given number n.

Let's see the steps to solve the problem.

  • Initialise the n-ary tree.

  • Initialise the count to 0.

  • Increment the count by 1 when you find a node whose value is greater than n.

  • Get the children of the current node.

  • Iterate over all the children and recursively call the same function to count nodes.

  • Return the count.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
struct Node {
   int data;
   vector<Node*> child;
};
Node* getNewNode(int data) {
   Node* temp = new Node;
   temp->data = data;
   return temp;
}
int getGreaterElementsCount(Node* root, int n) {
   if (root == NULL)
      return 0;
   int count = 0;
   if (root->data > n) {
      count++;
   }
   int nodeChildrenCount = root->child.size();
   for (int i = 0; i < nodeChildrenCount; i++) {
      Node* child = root->child[i];
      count += getGreaterElementsCount(child, n);
   }
   return count;
}
int main() {
   Node* root = getNewNode(1);
   (root->child).push_back(getNewNode(2));
   (root->child).push_back(getNewNode(3));
   (root->child).push_back(getNewNode(4));
   (root->child[0]->child).push_back(getNewNode(5));
   (root->child[0]->child).push_back(getNewNode(5));
   (root->child[1]->child).push_back(getNewNode(6));
   (root->child[1]->child).push_back(getNewNode(6));
   (root->child[1]->child).push_back(getNewNode(7));
   (root->child[2]->child).push_back(getNewNode(8));
   (root->child[2]->child).push_back(getNewNode(8));
   (root->child[2]->child).push_back(getNewNode(9));
   int n = 2;
   cout << getGreaterElementsCount(root, n) << endl;
   return 0;
}

Output

If you run the above code, then you will get the following result.

10

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

raja
Published on 03-Jul-2021 08:19:18
Advertisements