LinkedIn Interview Question: Print out a binary tree with ... | Glassdoor

Interview Question

Software Engineer Interview Mountain View, CA

Print out a binary tree with each level printed on its own


Interview Answer

4 Answers


Figuring out that you need an in-order traversal isn't too tough. Figuring out where to put the line breaks takes a little more work. I solved it, with some help on that second part.

Interview Candidate on Jan 5, 2014

Just print BFS

Anonymous on Feb 19, 2014

BFS with some modification looks correct, but how would do this with in-order traversal?

Anonymous on Apr 7, 2014

//Breadth First Search, traverse tree and print it out level-by-level

public class TreeNode{
 public int data;
 public int level;
 public TreeNode left;
 public TreeNode right;
 public TreeNode(int d, int l){ = d;
  this.level = l;
  this.left = null;
  this right = null;

public class BinaryTree{
 public TreeNode root;
 public BinaryTree(){
  this.root = null;

 public void setLevels(TreeNode node, int l){
  if (node != null){
   node.level = l;
   setLevels(node.left, level + 1);
   setLevels(node.right, level + 1);


 public void printEachTreeLevel(TreeNode root){
  Queue<div>treeQueue = new LinkedList<div>();
  if (root == null){
  //set levels, just in case
  setLevels(root, 0);
  //Start Breadth first traversal of tree
  while (!(treeQueue.size() == 0)){
   TreeNode node = treeQueue.remove();
   System.out.print( + " ");
   //If we are at the end of a level, start a new line
   if (node.level != treeQueue.peek().level){
   if (node.left != null){
   if (node.right != null){

Dan on Jan 10, 2015

Add Answers or Comments

To comment on this, Sign In or Sign Up.