LinkedIn Interview Question

Print a tree level by level

Interview Answers

Anonymous

Apr 10, 2012

Details: use a queue. Enqueue the root. dequeue it, print it and and enqueue its children. Continue dequeuing, printing and enqueuing child nodes until the queue is empty.

2

Anonymous

Mar 19, 2012

use BFS(Breadth First Search) to print the tree level by level

1

Anonymous

May 13, 2012

Ask interviewer what he/she means by "level by level". Suppose it means one line per level, then all above answers failed. Use a queue, enqueue head. Enqueue null to indicate end of level. While (queue is not empty) { dequeue an element; // n peek an element; // next if (n is not null) { enqueue its children; print n; if (next is null) { print linebreak; enqueue null; } }

2

Anonymous

May 7, 2012

A simple solution is to start from the root of the binary tree push every left child to 2*i and right child to 2*i+1 location of a temp array. Then when there all the elements in the binary tree are traversed then print the array. O(nlogn)