Count Non-Leaf nodes in a Binary Tree
Last Updated :
03 Apr, 2023
Given a Binary tree, count the total number of non-leaf nodes in the tree
Examples:
Input :
Output :2
Explanation
In the above tree only two nodes 1 and 2 are non-leaf nodes
We recursively traverse the given tree. While traversing, we count non-leaf nodes in left and right subtrees and add 1 to the result
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node* left;
struct Node* right;
};
struct Node* newNode( int data)
{
struct Node* node = new Node;
node->data = data;
node->left = node->right = NULL;
return (node);
}
int countNonleaf( struct Node* root)
{
if (root == NULL || (root->left == NULL &&
root->right == NULL))
return 0;
return 1 + countNonleaf(root->left) +
countNonleaf(root->right);
}
int main()
{
struct Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
cout << countNonleaf(root);
return 0;
}
|
Java
class GfG {
static class Node {
int data;
Node left;
Node right;
}
static Node newNode( int data)
{
Node node = new Node();
node.data = data;
node.left = null ;
node.right = null ;
return (node);
}
static int countNonleaf(Node root)
{
if (root == null || (root.left == null &&
root.right == null ))
return 0 ;
return 1 + countNonleaf(root.left) +
countNonleaf(root.right);
}
public static void main(String[] args)
{
Node root = newNode( 1 );
root.left = newNode( 2 );
root.right = newNode( 3 );
root.left.left = newNode( 4 );
root.left.right = newNode( 5 );
System.out.println(countNonleaf(root));
}
}
|
Python3
class newNode:
def __init__( self ,data):
self .data = data
self .left = self .right = None
def countNonleaf(root):
if (root = = None or (root.left = = None and
root.right = = None )):
return 0
return ( 1 + countNonleaf(root.left) +
countNonleaf(root.right))
if __name__ = = '__main__' :
root = newNode( 1 )
root.left = newNode( 2 )
root.right = newNode( 3 )
root.left.left = newNode( 4 )
root.left.right = newNode( 5 )
print (countNonleaf(root))
|
C#
using System;
class GfG
{
class Node {
public int data;
public Node left;
public Node right;
}
static Node newNode( int data)
{
Node node = new Node();
node.data = data;
node.left = null ;
node.right = null ;
return (node);
}
static int countNonleaf(Node root)
{
if (root == null || (root.left == null &&
root.right == null ))
return 0;
return 1 + countNonleaf(root.left) +
countNonleaf(root.right);
}
public static void Main(String[] args)
{
Node root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
root.left.left = newNode(4);
root.left.right = newNode(5);
Console.WriteLine(countNonleaf(root));
}
}
|
Javascript
<script>
class Node
{
constructor(data) {
this .left = null ;
this .right = null ;
this .data = data;
}
}
function newNode(data)
{
let node = new Node(data);
return (node);
}
function countNonleaf(root)
{
if (root == null || (root.left == null &&
root.right == null ))
return 0;
return 1 + countNonleaf(root.left) +
countNonleaf(root.right);
}
let root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
root.left.left = newNode(4);
root.left.right = newNode(5);
document.write(countNonleaf(root));
</script>
|
Time Complexity: O(N)
Space Complexity: If we don’t consider the size of the stack for function calls then O(1) otherwise O(h) where h is the height of the tree.
Another Approach(Iterative):
The given problem can be solved by using the Level Order Traversal.
Follow the steps below to solve the problem:
1) Create a queue(q) and initialize count variable with 0, and store the nodes in q along wise level order and iterate for next level.
2) Perform level order traversal and check if current node is a non-leaf node(have right or left any one child) then increment the count variable.
3) After completing the above steps, return count variable.
Below is the implementation of above approach:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node{
int data;
struct Node* left;
struct Node* right;
};
Node* newNode( int data){
Node *new_node = new Node();
new_node->data = data;
new_node->left = NULL;
new_node->right = NULL;
return new_node;
}
int getLeafCount(Node* root){
queue<Node*> q;
q.push(root);
int count = 0;
while (!q.empty()){
Node* temp = q.front();
q.pop();
if (temp->left != NULL || temp->right != NULL)
count++;
if (temp->left) q.push(temp->left);
if (temp->right) q.push(temp->right);
}
return count;
}
int main(){
struct Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
cout << "Non-Leaf count of the tree is : " << getLeafCount(root) << endl;
return 0;
}
|
Java
import java.util.LinkedList;
import java.util.Queue;
class Node{
public int data;
public Node left, right;
public Node( int data){
data = data;
left = right = null ;
}
}
public class BinaryTree{
static Node newNode( int data){
return new Node(data);
}
static int getLeafCount(Node root){
Queue<Node> q = new LinkedList<Node>();
q.add(root);
int count = 0 ;
while (!q.isEmpty()){
Node temp = q.poll();
if (temp.left != null || temp.right != null ){
count++;
}
if (temp.left != null ) q.add(temp.left);
if (temp.right != null ) q.add(temp.right);
}
return count;
}
public static void main(String args[]){
Node root = newNode( 1 );
root.left = newNode( 2 );
root.right = newNode( 3 );
root.left.left = newNode( 4 );
root.left.right = newNode( 5 );
System.out.println( "Non-leaf count of the tree is : " + getLeafCount(root));
}
}
|
Python3
class Node:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
def newNode(data):
return Node(data)
def getLeafCount(root):
q = []
q.append(root)
count = 0
while ( len (q) > 0 ):
temp = q.pop( 0 )
if (temp.left is not None or temp.right is not None ):
count + = 1
if (temp.left is not None ):
q.append(temp.left)
if (temp.right is not None ):
q.append(temp.right)
return count
root = newNode( 1 )
root.left = newNode( 2 )
root.right = newNode( 3 )
root.left.left = newNode( 4 )
root.left.right = newNode( 5 )
print ( "Non-Leaf count of the tree is :" , end = " " )
print (getLeafCount(root))
|
C#
using System;
using System.Collections.Generic;
public class Node{
public int data;
public Node left, right;
public Node( int item){
data = item;
left = null ;
right = null ;
}
}
public class BinaryTree
{
static Node newNode( int data){
return new Node(data);
}
static int getLeafCount(Node root)
{
Queue<Node> q = new Queue<Node>();
q.Enqueue(root);
int count = 0;
while (q.Count != 0){
Node temp = q.Dequeue();
if (temp.left != null || temp.right != null ) count++;
if (temp.left != null ) q.Enqueue(temp.left);
if (temp.right != null ) q.Enqueue(temp.right);
}
return count;
}
public static void Main(){
Node root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
root.left.left = newNode(4);
root.left.right = newNode(5);
Console.WriteLine( "Non-Leaf count of the tree is : " + getLeafCount(root));
}
}
|
Javascript
class Node{
constructor(data){
this .data = data;
this .left = null ;
this .right = null ;
}
}
function newNode(data){
return new Node(data);
}
function getLeafCount(root)
{
let q = [];
q.push(root);
let count = 0;
while (q.length > 0){
let temp = q.shift();
if (temp.left != null || temp.right != null ) count++;
if (temp.left) q.push(temp.left);
if (temp.right) q.push(temp.right);
}
return count;
}
let root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
root.left.left = newNode(4);
root.left.right = newNode(5);
console.log( "Non-Leaf count of the tree is: " +getLeafCount(root));
|
Output
Non-Leaf count of the tree is : 2
Time Complexity: O(N) where N is the number of nodes in given binary tree.
Auxiliary Space: O(N) due to queue data structure.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...