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:
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.
- Count of nodes in a Binary tree with immediate children as its factors
- Count of nodes in a Binary Tree whose immediate children are co-prime
- Difference between sums of odd level and even level nodes of a Binary Tree
- Sum of all nodes at Kth level in a Binary Tree
- Swap Nodes in Binary tree of every k'th level
- Nodes at Kth level without duplicates in a Binary Tree
- Print nodes between two given level numbers of a binary tree
- Count the number of nodes at a given level in a tree using DFS
- Count the number of nodes at given level in a tree using BFS.
- Print all the nodes except the leftmost node in every level of the given binary tree
- Print all nodes except rightmost node of every level of the Binary Tree
- Print even positioned nodes of even levels in level order of the given binary tree
- Print odd positioned nodes of even levels in level order of the given binary tree
- Print extreme nodes of each level of Binary Tree in alternate order
- Print even positioned nodes of odd levels in level order of the given binary tree
- Print odd positioned nodes of odd levels in level order of the given binary tree
- Queries to find the maximum Xor value between X and the nodes of a given level of a perfect binary tree
- Given a n-ary tree, count number of nodes which have more number of children than parents
- Recursive Program to Print extreme nodes of each level of Binary Tree in alternate order
- General Tree (Each node can have arbitrary number of children) Level Order Traversal
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.