« Count number of nodes greater than x
Count nodes greater than x
Given a tree and an integer x, find and return the number of nodes which contains data greater than x.
Input format:
The first line of input contains data of the nodes of the tree in level order form. The order is: data for root node, number of children to root node,
data of each of child nodes and so on and so forth for each node. The data of the nodes of the tree is separated by space.
The following line contains an integer, that denotes the value of x.
Output Format :
The first and only line of output prints the count of nodes greater than x.
Constraints:
Time Limit: 1 sec
Sample Input 1 :
10 3 20 30 40 2 40 50 0 0 0 0
35
Sample Output 1 :
3
Sample Input 2 :
10 3 20 30 40 2 40 50 0 0 0 0
10
Sample Output 2:
5
1#include <iostream>2#include <queue>3#include <vector>4using namespace std;56template <typename T>7class TreeNode {8 public:9 T data;10 vector<TreeNode<T>*> children;1112 TreeNode(T data) { this->data = data; }1314 ~TreeNode() {15 for (int i = 0; i < children.size(); i++) {16 delete children[i];17 }18 }19};2021int getLargeNodeCount(TreeNode<int>* root, int x) {22 if(root == NULL){23 return 0;24 }25 int ans = 0;26 if(root->data > x){27 ans++;28 }2930 for(int i=0; i<root->children.size(); i++){31 ans = ans + getLargeNodeCount(root->children[i], x);32 }33 return ans;34}3536TreeNode<int>* takeInputLevelWise() {37 int rootData;38 cin >> rootData;39 TreeNode<int>* root = new TreeNode<int>(rootData);4041 queue<TreeNode<int>*> pendingNodes;4243 pendingNodes.push(root);44 while (pendingNodes.size() != 0) {45 TreeNode<int>* front = pendingNodes.front();46 pendingNodes.pop();47 int numChild;48 cin >> numChild;49 for (int i = 0; i < numChild; i++) {50 int childData;51 cin >> childData;52 TreeNode<int>* child = new TreeNode<int>(childData);53 front->children.push_back(child);54 pendingNodes.push(child);55 }56 }5758 return root;59}6061int main() {62 TreeNode<int>* root = takeInputLevelWise();63 int x;64 cin >> x;65 cout << getLargeNodeCount(root, x);66}