Count nodes with two children at level L in a Binary Tree
Given a Binary tree, the task is to count the number of nodes with two children at a given level L.
Input: 1 / \ 2 3 / \ \ 4 5 6 / / \ 7 8 9 L = 2 Output: 1 Input: 20 / \ 8 22 / \ / \ 5 3 4 25 / \ / \ \ 1 10 2 14 6 L = 3 Output: 2
Approach: Initialize a variable count = 0. Recursively traverse the tree in a level order manner. If the current level is same as the given level, then check whether the current node has two children. If it has two children then increment the variable count.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.