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

line.

0

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
3

Just print BFS

Anonymous on Feb 19, 2014
0

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

Anonymous on Apr 7, 2014
0

//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){
this.data = 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){
return;
}
//set levels, just in case
setLevels(root, 0);
//Start Breadth first traversal of tree
treeQueue.clear();
while (!(treeQueue.size() == 0)){
TreeNode node = treeQueue.remove();
System.out.print(node.data + " ");
//If we are at the end of a level, start a new line
if (node.level != treeQueue.peek().level){
System.out.println();
}
if (node.left != null){