How to implement Level Order Traversal in Binary Tree?
💻 coding

How to implement Level Order Traversal in Binary Tree?

1 min read 194 words
1 min read
ShareWhatsAppPost on X
  • 1Level order traversal visits every node on a level before moving to the next level, following a breadth-first search approach.
  • 2The Java implementation uses a queue to facilitate the level order traversal of a binary tree.
  • 3The time complexity of level order traversal is O(n), processing each node in the tree once.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"Level order traversal visits every node on a level before moving to the next level, following a breadth-first search approach."

How to implement Level Order Traversal in Binary Tree?

Trees can also be traversed in level-order, where we visit every node on a level before going to a lower level. This search is referred to as a breadth-first search (BFS), as the search tree is broadened as much as possible on each depth before going to the next depth.

Java implementation of level order traversal is as below:

package askgif.tree;

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

class Node
{
 int data;
 Node left, right;
 
 public Node(int item)
 {
 data = item;
 left = right = null;
 }
}

class BinaryTree
{
 Node root;
 
 BinaryTree()
 {
 root = null;
 }
 
}

public class TreeQuestions {

	public static void main(String[] args) {
		BinaryTree binaryTree = new BinaryTree();
		Node root = new Node(1);
		binaryTree.root = root;
		binaryTree.root.left = new Node(2);
		binaryTree.root.right = new Node(3);
		binaryTree.root.left.left = new Node(4);
		binaryTree.root.left.right = new Node(5);
 
 PrintLevelOrderTraversal(root);

	}

	private static void PrintLevelOrderTraversal(Node treeNode) {
		if(treeNode == null)
			return;
		
		Queue<Node> queue = new LinkedList<Node>();
		queue.add(treeNode);
		while(!queue.isEmpty()) {
			Node temp = queue.remove();
			System.out.println(temp.data);
			if(temp.left != null)
				queue.add(temp.left);
			if(temp.right != null)
				queue.add(temp.right);
		}
		
	}

}
output:

1
2
3
4
5

Time Complexity: O(n). as we are processing each node of the tree at once.

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 14 August 2018 · 1 min read · 194 words

Part of AskGif Blog · coding

You might also like

How to implement Level Order Traversal in Binary Tree? | AskGif Blog