[Solved] Level them All! Contest Problem

Level them All!: You are given a binary tree and an integer L. Count the number of nodes on that level.
Note: L may be greater than maximum possible level. In such case answer is 0 nodes.

Input Format:
The first line of input contains T denoting the number of testcases. T testcases follow. Each testcase contains two lines of input. The first line contains number of edges and level L. The second line contains the relation between nodes.

Output Format:
For each testcase, in a new line, print the number of nodes on given level.

Your Task:
You need to complete the function Count which takes Root and level and return Number of nodes at that level.

Constraints:
1 <= T <= 30
1 <= Number of nodes <= 100
1 <= Data of a node <= 1000
 

Example:
Input:

2
2 1
1 2 L 1 3 R
4 3
10 20 L 10 30 R 20 40 L 20 60 R
Output:
1
2

Explanation:
Testcase1: The tree is
        1
     /      \
   2        3
On first level there is only one node.
Testcase2: The tree is
                           10
                        /        \
                     20         30
                  /       \
               40       60
On third level there are 2 nodes.

Solution

int ans=0;

void rec(Node *node,int lvl,int req){
    if(node==NULL) return ;
    if(lvl==req) ans++;
    rec(node->left,lvl+1,req);
    rec(node->right,lvl+1,req);
}

int Count(Node *node,int L){
    
    ans=0;
    rec(node,1,L);
    return ans;

    
}
class GfG {
    
    int ans=0;
    void rec (Node node, int lvl, int req){
        if(node==null) return;
        if(lvl==req)ans++;
        rec(node.left, lvl+1, req);
        rec(node.right, lvl+1, req);
    }
    
    int getNumNodesAtLevel(Node root, int lvl) {
        ans=0;
        rec(root, 1, lvl);
        return ans;
    }
}
def rec(node,lvl,req):
    global ans
    if(node == None):
        return
    if(lvl == req):
        ans += 1
    rec(node.left,lvl+1,req)
    rec(node.right,lvl+1,req)


def count(node,l):
    global ans
    ans = 0
    rec(node,1,l)
    return ans

Happy Learning – If you require any further information, feel free to contact me.

Share your love
Saurav Hathi

Saurav Hathi

I'm currently studying Bachelor of Computer Science at Lovely Professional University in Punjab.

📌 Nodejs and Android 😎
📌 Java

Articles: 444

Leave a Reply

Your email address will not be published. Required fields are marked *