Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #9 from rusyasoft/patch-1
BST level-order-traversal
- Loading branch information
Showing
1 changed file
with
55 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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); | ||
} | ||
} |