# Coding Challenge Day-13: Problem 1: Level-order traversal of a Binary tree

Hello! So I’m doing a 100 day coding challenge where I solve a few questions every day and thought of posting them here on my blog so that you guys can join the challenge too!

Welcome to Coding challenge Day 13: Problem 1! Be sure to post your answers, queries etc in the comments!

Problem: Level-order traversal of a Binary tree

Sample:

Output:

Level: 0
1
Level: 1
2
3
Level: 2
4
5
6
7
Level: 3

Solution:

``````package tree.binarytree;

import java.util.Queue;

public class Program011level_order_traversal {

static class Node{
int data;
Node left, right;

public Node(int d){
data=d;
left=right=null;
}
}

static class Binary_tree{
Node root;

public Binary_tree(){
root=null;
}

public void add_left (Node parent_node, Node node){
parent_node.left= node;
}

public void add_right (Node parent_node, Node node){
parent_node.right= node;
}

public void level_order_traversal(){
Node node= root;
Node level_node= new Node(-1);
Node previous_node= root;
int level=0;

System.out.println("Level: 0");

while(!queue.isEmpty()){
Node front_node= queue.poll();
if(front_node.data==-1){
level++;
if(previous_node.data!=-1){
System.out.println("Level: " + level);
}
} else{
System.out.println(front_node.data);
if(front_node.left!=null){
}

if(front_node.right!=null){
}
}

previous_node= front_node;
}
}

}

public static void main (String [] args){
Binary_tree tree= new Binary_tree();

tree.root= new Node(1);

Node node2= new Node(2);

Node node3= new Node(3);

Node node4= new Node (4);

Node node5= new Node(5);

Node node6= new Node(6);

Node node7= new Node(7);

tree.level_order_traversal();
}
}

``````

Happy Learning!!

This site uses Akismet to reduce spam. Learn how your comment data is processed.