Facebook Interview Question
Software Engineer / DevelopersBut how would you know when to hit a new line?
Eg
1
2 3 4
5 6 7 8 9
I suppose this is per level printing..
You need to know the structure of the tree..or can use 2 queues and keep switching between them...add children to second queue while iterating over first one till its empty...then switch first and second queue and again perform...pretty poor space complexity but time will be theta(n).
1. Create two Queues A, B.
2. Start from Root.
3. Put all childrens into A.
4. Do a While A is not Empty. Print the Node, put all thier children into QueueB.
5. Now copy B into A. Repeat 4.
6. if A is empty and B is empty. Quit.
Don't understand why we need two queues, one is sufficient. Steps should be like,
1. push root to the queue.
2. if queue is NOT empty
pop the element from the queue.
print it.
if the element has any children,
push all its children to the queue.
Repeat step 2 until queue is empty.
Any comments?
Added null after all nodes in one level are added in queue, as an indicator of one level traversal
int min_depth(BT t)
{
Queue q;
Enqueue(Q,t);
Enqueue(q,null);
while(!IsEmptyQ(q))
{
node=Dequeue(q);
if(q==null)
{
printf("\n");
if(!IsEmptyQ(q))
Enqueue(q,null);
}
else
{
printf("%d ",node->data);
Enqueue all childs of node in q;
}
}
}
public static class Node {
public Node(String value) {
this.value = value;
}
public String value;
public List<Node> children = new ArrayList<>();
}
public static void printTreeByLevels(Node root){
List<Node> rootLevel = new ArrayList<>();
rootLevel.add(root);
printLevel(rootLevel);
}
public static void printLevel(List<Node> level){
List<Node> nextLevel = new ArrayList<>();
for (Node n : level){
System.out.printf("%s ", n.value);
nextLevel.addAll(n.children);
}
if (!nextLevel.isEmpty()) {
System.out.println("\n");
printLevel(nextLevel);
}
}
- dumbcoder November 22, 2010