Skip to content

Instantly share code, notes, and snippets.

@adeydas
Created June 17, 2015 01:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adeydas/d209dca13927fb8a63fd to your computer and use it in GitHub Desktop.
Save adeydas/d209dca13927fb8a63fd to your computer and use it in GitHub Desktop.
Print LO-T
package ws.abhis.interviews.amazon;
import junit.framework.TestCase;
import ws.abhis.interviews.TreeNode;
import java.util.LinkedList;
import java.util.Queue;
/**
* Level order traversal and print each level in one line.
*/
public class PrintLevelOrder extends TestCase {
public void solution(TreeNode root) {
if (root == null)
return;
Queue<TreeNode> queue = new LinkedList<>();
int current = 1, next = 0;
queue.add(root);
while (!queue.isEmpty()) {
TreeNode n = queue.remove();
System.out.print(n.val + "\t");
current = current-1;
if (n.left != null) {
queue.add(n.left);
next = next+1;
}
if (n.right != null) {
queue.add(n.right);
next = next+1;
}
if (current == 0) {
current = next;
next = 0;
System.out.println();
}
}
}
public void testOne() {
TreeNode one = new TreeNode(1);
TreeNode two = new TreeNode(2);
TreeNode three = new TreeNode(3);
TreeNode four = new TreeNode(4);
TreeNode five = new TreeNode(5);
TreeNode six = new TreeNode(6);
TreeNode seven = new TreeNode(7);
one.left = two; one.right = three;
two.left = four; two.right = five;
three.left = six; three.right = seven;
solution(one);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment