« Count Leaf Nodes

Count leaf nodes

Given a generic tree, count and return the number of leaf nodes present in the given tree.

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.

Output Format :

The first and only line of output prints the count of leaf nodes present in the given tree.

Constraints:

Time Limit: 1 sec

Sample Input 1 :

10 3 20 30 40 2 40 50 0 0 0 0

Sample Output 1 :

4

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 getLeafNodeCount(TreeNode<int>* root) {
22 if(root->children.size() == 0){
23 return 1;
24 }
25 int ans = 0;
26 for(int i=0; i<root->children.size() ; i++){
27 ans += getLeafNodeCount(root->children[i]);
28 }
29 return ans;
30}
31
32TreeNode<int>* takeInputLevelWise() {
33 int rootData;
34 cin >> rootData;
35 TreeNode<int>* root = new TreeNode<int>(rootData);
36
37 queue<TreeNode<int>*> pendingNodes;
38
39 pendingNodes.push(root);
40 while (pendingNodes.size() != 0) {
41 TreeNode<int>* front = pendingNodes.front();
42 pendingNodes.pop();
43 int numChild;
44 cin >> numChild;
45 for (int i = 0; i < numChild; i++) {
46 int childData;
47 cin >> childData;
48 TreeNode<int>* child = new TreeNode<int>(childData);
49 front->children.push_back(child);
50 pendingNodes.push(child);
51 }
52 }
53
54 return root;
55}
56
57int main() {
58 TreeNode<int>* root = takeInputLevelWise();
59 cout << getLeafNodeCount(root);
60}