Skip to content

Instantly share code, notes, and snippets.

@AlinaWithAFace
Created April 21, 2018 01:41
Show Gist options
  • Save AlinaWithAFace/7ebf31fa06afd9a8c35609e48163a61e to your computer and use it in GitHub Desktop.
Save AlinaWithAFace/7ebf31fa06afd9a8c35609e48163a61e to your computer and use it in GitHub Desktop.
import java.util.*;
import java.io.*;
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> nodeQueue = new LinkedList<>();
nodeQueue.add(root);
while (!nodeQueue.isEmpty()) {
Node myNode = nodeQueue.remove();
System.out.printf("%d ", myNode.data);
if (null != myNode.left) {
nodeQueue.add(myNode.left);
}
if (null != myNode.right) {
nodeQueue.add(myNode.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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment