Last active
March 23, 2022 19:19
-
-
Save obasekiosa/ad5c90e8ce59ab2abde78165f475e9c1 to your computer and use it in GitHub Desktop.
Hacker Rank - Tree: Level Order Traversal Challenge https://www.hackerrank.com/challenges/tree-level-order-traversal/problem
This file contains hidden or 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
import java.util.*; | |
import java.io.*; | |
class Solution { | |
class Node { | |
Node left; | |
Node right; | |
int data; | |
Node(int data) { | |
this.data = data; | |
left = null; | |
right = null; | |
} | |
} | |
/* | |
class Node | |
int data; | |
Node left; | |
Node right; | |
*/ | |
public static void levelOrder(Node root) { | |
if (root != null) { | |
LinkedList<Node> q = new LinkedList<>(); | |
q.add(root); | |
while (!q.isEmpty()) { | |
Node curr = q.poll(); | |
if (curr.left != null) q.offer(curr.left); | |
if (curr.right !=null) q.offer(curr.right); | |
System.out.print(curr.data + " "); | |
} | |
} | |
System.out.println(); | |
} | |
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 scan = new Scanner(System.in); | |
int t = scan.nextInt(); | |
Node root = null; | |
while(t-- > 0) { | |
int data = scan.nextInt(); | |
root = insert(root, data); | |
} | |
scan.close(); | |
levelOrder(root); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment