×

Level order Traversal of a Binary Tree in Java

In Java, a level order traversal of a tree structure is also referred to as the breadth-first traversal of the binary tree.

Regarding the subsequent binary tree:

Level order Traversal of a Binary Tree in Java

Level order traversal is as follows: 18 20 30 60 34 45 65 12 50 98 82 31 59 71 41

Using Recursion

It is possible to navigate a binary tree's level order using recursion. The recursive technique must take care of the left and right subtrees. The same is more fully demonstrated in the code below.

Implementation

Let's use the aforementioned pseudo-code to carry out the binary tree's level order traverse.

BTLevelOrder.java

// a class for producing binary tree nodes 
// A left and right reference
// as well as the node's value
// are contained in each binary tree node. 
class TreeNode   
{  
// for maintaining the node's value
int v;  
  
// to discuss the other nodes  
TreeNode l, r;  
  
// builder for the class 
// The construct TreeNode initializes the class fields.  
public TreeNode(int i)  
{  
v = i;  
r = l = null;  
}  
}  
  
public class BTLevelOrder    
{  
// the Binary Tree's top node, or root  
TreeNode r1;  
  
// function Object() { [native code] } for the BTree class  
public BTLevelOrder() { r1 = null; }  
  
// a technique for visualizing the binary tree's level order traversal 
void displayLevelOrder()  
{  
int ht1 = treeHeight(r1);  
int j;  
  
for (j = 1; j <= ht1; j++)  
{  
displayCurrentLevel(r1, j);  
}  
}  
  
// discovering the binary tree's "height"
// Keep in mind that the lengthiest path 
// from the topmost node (root node) to the leaf node, 
// which is the farthest from the root node, 
// determines the tree's height. 
int treeHeight(TreeNode r1)  
{  
if (r1 == null)  
{  
return 0;  
}  
else   
{  
// determining the left and right subtrees' heights  
int lh1 = treeHeight(r1.l);  
int rh1 = treeHeight(r1.r);  
  
// grabbing the bigger one  
if (lh1 > rh1)  
{  
return (lh1 + 1);  
}  
else  
{  
return (rh1 + 1);  
}  
}  
}  
  
// Nodes in the current level that can be printed  
void displayCurrentLevel(TreeNode r1, int l)  
{  
// Null indicates there is nothing to print.  
if (r1 == null)  
{  
return;  
}  
  
// If l == 1, 
// then there is just one node in the binary tree.  
if (l == 1)  
{  
System.out.print(r1.v + " ");  
}  
  
// We must search both the left and 
// the right sides of the current node since l > 1 denotes 
// that either node is present on the left side 
// of the current node, the right side 
// of the current node, or both sides.
else if (l > 1)   
{  
displayCurrentLevel(r1.l, l - 1);  
displayCurrentLevel(r1.r, l - 1);  
}  
}  
  
// main method  
public static void main(String args[])  
{  
// creating an instance of the class BTLevelOrder   
BTLevelOrder  t = new BTLevelOrder ();  
  
// root node  
t.r1 = new TreeNode(18);  
  
// the remaining tree nodes  
t.r1.l = new TreeNode(20);  
t.r1.r = new TreeNode(30);  
t.r1.l.l = new TreeNode(60);  
t.r1.l.r = new TreeNode(34);  
t.r1.r.l = new TreeNode(45);  
t.r1.r.r = new TreeNode(65);  
t.r1.l.l.l = new TreeNode(12);  
t.r1.l.l.r = new TreeNode(50);  
t.r1.l.r.l = new TreeNode(98);  
t.r1.l.r.r = new TreeNode(82);  
t.r1.r.l.l = new TreeNode(31);  
t.r1.r.l.r = new TreeNode(59);  
t.r1.r.r.l = new TreeNode(71);  
t.r1.r.r.r = new TreeNode(41);  
System.out.println(" Binary tree level order traversal is ");  
t.displayLevelOrder();  
}  
}  

Output:

Level order Traversal of a Binary Tree in Java

Time Complexity:

The program's worst-case time complexity, where n is the total number of nodes in a binary tree, is O(n2). Remember that a skewed tree results in the worst-case scenario.

Space Complexity:

The program's worst-case space complexity, where n is the total number of nodes in a binary tree, is O(n). Remember that a skewed tree results in the worst-case scenario. The O(n) space call stack is used by the displayCurrentLevel() method for skewed trees. The space required in our example is O(log(n)), which is equal to the height of a balanced tree because the tree is balanced.

Using Queue

A queue can also be used to traverse a binary tree's level order. We initially use a queue to group all of a node's children. The left youngster is put in front of the right child in the queue. Because a queue functions in accordance with the FIFO (First In First Out) rule, which stipulates that the left child comes out first following by the right child, the level-ordered traverse of the tree is made possible. For a better understanding, let's look at the implementation first.

Implementation

BTLevelOrder1.java

// importing the program's necessary 
// classes for queues and linked lists 
import java.util.Queue;  
import java.util.LinkedList;  
  
  
// a class for producing binary tree nodes
// A left and right reference, as well as 
// the node's value, is contained in 
// each binary tree node. 
class TreeNode   
{  
// for maintaining the node's value  
int v;  
  
// to discuss the other nodes 
TreeNode l, r;  
  
// builder for the class 
// The construct TreeNode initializes the class fields.  
public TreeNode(int i)  
{  
v = i;  
r = l = null;  
}  
}  
  
// a class that prints a 
// level order of queue traversal
public class BTLevelOrder1   
{  
  
// the Binary Tree's top node, or root  
TreeNode r1;  
  
//  function Object() { [native code] } for the BTree class   
public BTLevelOrder1() { r1 = null; }  
  
// a technique for visualizing the binary tree's level order traversal  
void displayLevelOrder()  
{  
// making a blank queue  
Queue<TreeNode> q = new LinkedList<TreeNode>();  
  
// the node being added 
q.add(r1);  
  
while (!q.isEmpty())   
{  
// deleting the queue's front node 
TreeNode tNode = q.poll();  
  
//  the removed node's value.
System.out.print(tNode.v + " ");  
  
// Enqueue the left child if it's already there.   
if (tNode.l != null)   
{  
q.add(tNode.l);  
}  
  
// Enqueue the right child if it's already there.
if (tNode.r != null)   
{  
q.add(tNode.r);  
}  
}  
}  
  
// main method  
public static void main(String args[])  
{  
// creating an instance of the class BTLevelOrder1      
BTLevelOrder1  t = new BTLevelOrder1();  
  
// root node  
t.r1 = new TreeNode(18);  
  
// the remaining tree nodes
t.r1.l = new TreeNode(20);  
t.r1.r = new TreeNode(30);  
t.r1.l.l = new TreeNode(60);  
t.r1.l.r = new TreeNode(34);  
t.r1.r.l = new TreeNode(45);  
t.r1.r.r = new TreeNode(65);  
t.r1.l.l.l = new TreeNode(12);  
t.r1.l.l.r = new TreeNode(50);  
t.r1.l.r.l = new TreeNode(98);  
t.r1.l.r.r = new TreeNode(82);  
t.r1.r.l.l = new TreeNode(31);  
t.r1.r.l.r = new TreeNode(59);  
t.r1.r.r.l = new TreeNode(71);  
t.r1.r.r.r = new TreeNode(41);  
System.out.println(" Binary tree level order traversal is ");  
t.displayLevelOrder();  
}  
}  

Output:

Level order Traversal of a Binary Tree in Java

Time Complexity:

The program has an O(n) time complexity, where n is the overall number of nodes in a binary tree.

Space Complexity:

The program has an O(n) space complexity, where n is the number of nodes in a binary tree.

Comparative Analysis of the Two Methods

By contrast the time and spatial complexity of the two methods, we discover that employing a queue produces the desired output significantly more quickly. The queue program's time complexity and spatial complexity are independent of the way the nodes are arranged. In other words, the program's space and time complexity are unaffected by the skewness of the tree. This is impossible with a recursive method. The placement of the tree's nodes is crucial in the recursive technique.


Related Topics

Bin Packing Problem Java

Assigning some items with known weights to bins with consistent capacities is necessary for the bin packing problem. The goal is to use the smallest possible boxes while ensuring everything is put...

6 minutes read.

Level order Traversal of a Binary Tree in Java

In Java, a level order traversal of a tree structure is also referred to as the breadth-first traversal of the binary tree. Regarding the subsequent binary tree: Level order traversal is as...

5 minutes read.

How to Convert Timestamp to Date in Java

How to Convert Timestamp to Date in Java You can convert Timestamp to Date by using the constructor of Date class. It returns the long millisecond from Epoch (1st January 1970)...

2 minutes read.

Parallel Arrays Sort in Java

Sorting is a technique of arranging a sequence of numbers in ascending order, that is, the first number being lowest and gradually incrementing the numbers such that the last number...

7 minutes read.

Internal Working of ArrayList in Java

Java's version of a resizable array is called ArrayList. The dynamic growth of an array list ensures that there is always room for new elements. ArrayList's backing data structure is...

8 minutes read.

Java Subtract Days from Current Date

Dealing with date and time in Java is not a particularly challenging operation because Java has an API for date and time that simplifies duties for developers. There are two...

3 minutes read.

Creating API Document Javadoc tool

The JavaDoc utility is a document generator tool written in Java that generates standard documentation in HTML format. It parses declarations and documentation in a source file collection that describes...

3 minutes read.

Java Stringjoiner Class

StringJoiner is a class which is used to construct a sequence of characters which are separated by a delimiter. Optionally, it starts with a provided prefix and ended with the...

5 minutes read.

Object Definition in Java

In this article, you will be acknowledged about object in Java, its definition and how is this useful in writing the programs in Java. The comprehension of object-oriented technology depends on...

4 minutes read.

Recursion Program in Java

The recursion program in Java demonstrates the usage of recursion. The process by which a function/ method calls itself, again and again, is called recursion. Each recursive call is pushed...

10 minutes read.

Java Program to Print Permutations of String

A string is given and you need to print all the possible ways for that string. Permutation is arranging the characters of a string to get outputs from the given...

3 minutes read.

Various operations on HashSet in Java

In this article, you will be acknowledged about what is a HashSet in java and what are its operations in java programming language. The HashSet is a crucial part of...

3 minutes read.

Caesar Cipher Program in Java

It is among the most popular and straightforward encryption methods. With this method, each letter in the text is swapped out for a letter that is a certain number of...

3 minutes read.

Set Up the Environment in Java

The Java is regarded as the pure object-oriented programming language. The Java applications are first compiled into the byte-code and then run by using the JVM. The Java is the...

4 minutes read.

Character Array in Java

A character array is an array which holds values of character data types. It is different from a string array. The character array, string, and StringBuffer classes in the Java...

4 minutes read.

Swing Program in Java

Java Swing is part of Java Foundation Classes (JFC). The swing toolkit is used to generate Graphical User Interface (GUI) for programs written in Java. The Java swing API is...

4 minutes read.

Java Integer max() method

The max() method of Integer class returns the greater of two int values. It returns the same result as by calling Math.max. Syntax public static int max(int a, int b) Parameters The parameters ‘a’...

2 minutes read.

Why we use static in Java

Many reserved keywords in Java cannot be used as variable names or identifiers. Java uses static keywords frequently because of its effective memory management system. In most cases, you must...

3 minutes read.

Switch Case Program in Java

Switch Case Program in Java The switch case program in Java controls which code snippet gets executed on the basis of the value of the expression mentioned in the switch statement....

22 minutes read.

Difference Between Thread.start() and Thread.run()

In the Java programming language, the multi-threading concept consists of the start() and run() methods. Thread.start(): The thread's execution is initiated by invoking the start() method. The start() method operates two threads...

4 minutes read.