« 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;
5
6template <typename T>
7class TreeNode {
8 public:
9 T data;
10 vector<TreeNode<T>*> children;
11
12 TreeNode(T data) { this->data = data; }
13
14 ~TreeNode() {
15 for (int i = 0; i < children.size(); i++) {
16 delete children[i];
17 }
18 }
19};
20
21int 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 }
29
30 for(int i=0; i<root->children.size(); i++){
31 ans = ans + getLargeNodeCount(root->children[i], x);
32 }
33 return ans;
34}
35
36TreeNode<int>* takeInputLevelWise() {
37 int rootData;
38 cin >> rootData;
39 TreeNode<int>* root = new TreeNode<int>(rootData);
40
41 queue<TreeNode<int>*> pendingNodes;
42
43 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 }
57
58 return root;
59}
60
61int main() {
62 TreeNode<int>* root = takeInputLevelWise();
63 int x;
64 cin >> x;
65 cout << getLargeNodeCount(root, x);
66}