Site icon

Count non leaf nodes in binary tree in java (BFS /examples)

Fig 1: Non leaf nodes in binary tree

Let us look into the examples to find number of non leaf nodes in binary tree using breadth first search algorithm.

Example 1: number of non leaf nodes  having left child node

Fig 2: Non leaf left child node.

Example 2: number of non leaf nodes  having right child node

Fig 3: Non Leaf right child node

Example 3: number of non leaf nodes having left & right child nodes

Fig 4: Non leaf nodes – left & right child

Total number of non leaf nodes in a binary tree (Fig 5)

Fig 5: Non leaf nodes in binary tree

Time complexity of algorithm is O(n).

Program: count number of non leaf nodes in a binary tree using java

1.) CountNonLeafNodes Class:

package org.learn.Question;

import java.util.LinkedList;
import java.util.Queue;

public class CountNonLeafNodes {
	public static int countNonLeafNodes(Node root) {
		if (root == null) {
			System.out.println("Tree is empty");
			return -1;
		}
		int nNonLeaves = 0;
		Queue<Node> queue = new LinkedList<Node>();
		queue.offer(root);

		while (!queue.isEmpty()) {
			Node node = queue.poll();

			if (node.left != null || node.right != null) {
				nNonLeaves++;
			}
			if (node.left != null) {
				queue.offer(node.left);
			}
			if (node.right != null) {
				queue.offer(node.right);
			}
		}
		System.out.println("Non Leaf nodes in a binary tree : " + nNonLeaves);
		return nNonLeaves;
	}
}

2.) Node class:

package org.learn.Question;

public class Node {
	public int data;
	public Node left;
	public Node right;

	public Node(int num) {
		this.data = num;
		this.left = null;
		this.right = null;
	}

	public Node() {
		this.left = null;
		this.right = null;
	}

	public static Node createNode(int number) {
		return new Node(number);
	}
}

3.) App Class:

package org.learn.Client;

import org.learn.Question.CountNonLeafNodes;
import org.learn.Question.Node;

public class App {
	public static void main(String[] args) {
		// root level 0
		Node A = Node.createNode(60);
		// Level 1
		Node B = Node.createNode(20);
		Node C = Node.createNode(80);
		// Level 2
		Node D = Node.createNode(10);
		Node E = Node.createNode(30);
		Node F = Node.createNode(70);
		Node G = Node.createNode(90);
		// Level 3
		Node H = Node.createNode(65);
		Node I = Node.createNode(75);
		Node J = Node.createNode(85);
		Node K = Node.createNode(95);

		// connect Level 0 and 1
		A.left = B;
		A.right = C;
		// connect level 1 and level 2
		B.left = D;
		B.right = E;
		C.left = F;
		C.right = G;
		// connect level 2 and level 3
		D.left = H;
		F.right = I;
		G.left = J;
		G.right = K;

		CountNonLeafNodes.countNonLeafNodes(A);
	}
}

Output: number of non leaf nodes using level order traversal (java)

Non Leaf nodes in a binary tree : 6

Download Code – count non leaf nodes binary tree (BFS)

Exit mobile version