Site icon

Binary tree traversal – level order/breadth first search (java/example)

Examples of breadth first search algorithm.

Example 1:

Traverse the binary tree using level order traversal or BFS algorithm

Fig 1: Level order traversal – binary tree

In level order traversal, we will traverse the binary tree level by level (or breadth wise) and algorithm is as follows:

Fig 2: Breadth first search algorithm

Algorithm: Breadth first search tree traversal

Time complexity of algorithm is O(n).

Program- Level order binary tree traversal in java

1.) TreeTraversalBFS Class:

package org.learn.Question;

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

public class TreeTraversalBFS {

	public static void traverseBinaryTree(Node root) {
		if (root == null) {
			System.out.println("Tree is empty");
			return;
		}

		Queue<Node> queue = new LinkedList<Node>();
		queue.offer(root);

		while (!queue.isEmpty()) {
			Node node = queue.poll();
			System.out.printf("%d ", node.data);
			if (node.left != null) {
				queue.offer(node.left);
			}
			if (node.right != null) {
				queue.offer(node.right);
			}
		}
	}
}

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.Node;
import org.learn.Question.TreeTraversalBFS;

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
		F.left  = H;
		F.right = I;
		G.left  = J;
		G.right = K;
		
		System.out.println("Level order traversal or BFS of binary tree:");
		TreeTraversalBFS.traverseBinaryTree(A);
	}
}

Output: binary tree traversal – breadth first search

Level order traversal or BFS of binary tree:
60 20 80 10 30 70 90 65 75 85 95 

Code – binary tree traversal level order traversal (BFS)

 

Exit mobile version