एक n-ary ट्री और एक संख्या दी गई है, हमें दिए गए नंबर से बड़े नोड्स की संख्या गिननी है। आइए एक उदाहरण देखते हैं।
इनपुट
tree = [[4], [1, 2], [3, 5]] n = 2
आउटपुट
3
n से बड़े मान वाले 3 नोड्स हैं।
एल्गोरिदम
- n-ary ट्री को आरंभ करें।
- काउंट को 0 पर आरंभ करें।
- जब आपको कोई नोड मिले जिसका मान n से बड़ा है तो काउंट को 1 से बढ़ाएं।
- वर्तमान नोड के बच्चे प्राप्त करें।
- सभी बच्चों पर पुनरावृति करें और नोड्स गिनने के लिए समान फंक्शन को रिकर्सिवली कॉल करें।
- काउंट लौटाएं।
कार्यान्वयन
उपरोक्त एल्गोरिदम का C++ में कार्यान्वयन निम्नलिखित है:
#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; }आउटपुट
यदि आप उपरोक्त कोड चलाते हैं, तो आपको निम्नलिखित परिणाम मिलेगा।
10