Sollicitatievraag bij LinkedIn

Print a tree level by level

Antwoorden op sollicitatievragen

Anoniem

10 apr 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

Anoniem

19 mrt 2012

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

1

Anoniem

13 mei 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

Anoniem

7 mei 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)