Interview Question


Country: United States




Comment hidden because of low score. Click to expand.
1
of 1 vote

use BFS.. push the given root to a queue... following the root, push a "signal" element (such as NULL or -1 or so) to the stack... keep a global static levelCounter...
start dequeuing the queue until it becomes empty... push the children of the dequeued element into the queue... whenever you encounter the "signal" element, increment levelCounter...

print when you deem fit...

- JustCoding September 27, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 votes

Yes this is correct, though why anyone would ask you to this in a tree that is not a binary tree, I cant understand, but the essentials of a bfs search should work on a B Tree too

- T September 27, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

I am not getting the usage of stack. Why do you need the stack to track the signal element. When do you push or pop from the stack.

- Venki September 27, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

You need the signal element to mark the end of that particular level... I am using queues and not stack... stack will print DFS order... and here we would like BFS order right (level order) so...

So like in the given tree:

global variable (static int level = 0;)
print ("level %d: ", level)
initially Q is empty;
push root (1) to the Q;
push the signal element (say NULL) into Q;

so Q contains | (NULL) | 1 |

now (while !Q.empty())
{
          elem = dequeue (Q);
          if (elem == NULL)
          {
                  level ++;
                  print ("\nlevel %d: ", level);
          }
          else
          {
                    print ("%d ", elem);
                    push (children of elem into Q); /* I am assuming that since a given node can have multiple children, the child nodes are maintained as an array within the node; so traverse the array and push to the Q */
          }
}

and you will get the level order printing as desired.

Does this kinda make sense?

- JustCoding September 27, 2012 | Flag
Comment hidden because of low score. Click to expand.
0
of 0 votes

We can do this with just two variables to keep track of the number of nodes in the given level and the next level.

As an example:

void PrintLevelOrder(Node* root)
{
	if (root == null)
		return;

	int nodesAtCurrentLevel = 1;
	int nodesAtNextLevel = 0;

	Queue<Node*> items = new Queue<Node*>();
	items.Enqueue(root);

	while (!items.IsEmpty)
	{
		Node* current = items.Dequeue();
		printf("Level %d : %d", nodesAtCurrentLevel, current->data);
		nodesAtCurrentLevel--;

		if (current->Child != null)
		{
			foreach (Node* child in current->Child)
			{
				items.Enqueue(child);
				nodesAtNextLevel++;
			}
		}

		if (nodesAtCurrentLevel == 0)
		{
			nodesAtCurrentLevel = nodesAtNextLevel;
                        nodesAtNextLevel = 0;
		}
	}

}

- Venki September 28, 2012 | Flag
Comment hidden because of low score. Click to expand.
1
of 1 vote

private static void PrintInOrder(Node root)
{
    List<Node> currentLevel = new List<Node>();
    currentLevel.Add(root);
    printLevel(currentLevel);
}
private static void printLevel(List<Node> currentLevel)
{
    if (currentLevel.Count == 0) return;
    List<Node> nextLevel = new List<Node>();
    for (int i = 0; i < currentLevel.Count; i++)
    {
        Console.Write(currentLevel[i].Value + " ");
        nextLevel.AddRange(currentLevel[i].Children);
    }
    Console.WriteLine();
    printLevel(nextLevel);
}

- lukedude September 29, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Suppose the tree is like this:

1
/ | \
2 3 4
/ / | \
5 6 7 8


Output should be:
level 0: 1
level 1: 2 3 4
level 2: 5 6 7 8

How do you print the order, if it's not a binary tree?

- MobileEdge September 27, 2012 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

We use recursive call which takes, level as one of the parameters along with node. A hashmap to store the level and the list of nodes at that level. These nodes are collected during the tree traversal.

- bluesky September 27, 2012 | Flag Reply


Add a Comment
Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

Learn More

Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More