Skip to content

Commit

Permalink
Merge pull request #9 from rusyasoft/patch-1
Browse files Browse the repository at this point in the history
BST level-order-traversal
  • Loading branch information
miniam committed Oct 16, 2019
2 parents fae217f + fba3975 commit 385d6d7
Showing 1 changed file with 55 additions and 0 deletions.
55 changes: 55 additions & 0 deletions BST/BstLevelOrderTraversal.java
@@ -0,0 +1,55 @@
import java.util.*;
import java.io.*;


// solution for the problem https://www.hackerrank.com/challenges/30-binary-trees/problem

class Node{
Node left,right;
int data;
Node(int data){
this.data=data;
left=right=null;
}
}
class Solution{

static void levelOrder(Node root){
Queue<Node> queue = new LinkedList();
queue.add(root);

while(!queue.isEmpty()){
Node current = queue.remove();
System.out.print(current.data+" ");
if (current.left!=null) queue.add(current.left);
if (current.right!=null) queue.add(current.right);
}
}
public static Node insert(Node root,int data){
if(root==null){
return new Node(data);
}
else{
Node cur;
if(data<=root.data){
cur=insert(root.left,data);
root.left=cur;
}
else{
cur=insert(root.right,data);
root.right=cur;
}
return root;
}
}
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int T=sc.nextInt();
Node root=null;
while(T-->0){
int data=sc.nextInt();
root=insert(root,data);
}
levelOrder(root);
}
}

0 comments on commit 385d6d7

Please sign in to comment.