Site icon

Count non-leaf nodes (left & right child) in binary tree (java/ non-recursive/example)

Examples: Count non leaf nodes in a binary tree

Example 1: Number of non leaf nodes in binary tree (left & right children).

Given a binary tree shown in Fig 1, calculate the number of non leaf nodes having left & right child nodes.

Fig 1: Non leaf node (left & right child)
  if( node.left != null && node.right != null) {
    nNonLeaves++;    
   }  

Example 2:  Count non leaf nodes having left & right child (Fig 2).

Fig 2: Count non leaf nodes having left & right child

Time complexity of algorithm is O(n).

Program – count non leaf nodes in a binary tree using java

1.) CountNonLeafTwoChildren 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("Number of non-leaf nodes : " + 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(55);
		// Level 1
		Node B = Node.createNode(50);
		Node C = Node.createNode(40);
		// Level 2
		Node D = Node.createNode(25);
		Node E = Node.createNode(80);
		Node F = Node.createNode(45);
		Node G = Node.createNode(90);
		// Level 3
		Node H = Node.createNode(10);
		Node I = Node.createNode(35);
		Node J = Node.createNode(65);
		Node K = Node.createNode(75);

		// 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
		F.left = H;
		F.right = I;
		G.left = J;
		G.right = K;

		CountNonLeafNodes.countNonLeafNodes(A);
	}
}

Output – count non leaf nodes having left & right child nodes in java

Number of non-leaf nodes : 5

Download Code – Count Non Leaf nodes Binary Tree

 

Exit mobile version