Bloomberg LP Interview Question
Java DevelopersCountry: United States
Interview Type: In-Person
it can be done by the use of only one queue also...if the end of each level is marked by the null in the queue....
this is the pseudo code....
levelorder(struct node *root)
{
struct queue *q=createqueue();
if(root==NULL)
return;
levelorderutil(q,root);
}
levelorderutil(struct queue *q,struct node *root,int k)
{
if(root!=NULL)
enqueue(q,root);
if(k==0)
enqueue(q,NULL);
levelorderutil(q,root->left,k+1);
levelorderutil(q,root->right,k+1);
enqueue(q,NULL);
}
crkt me if i'm wrong.....
void printtree(Node* p,int level) {
vector<Node*> av;
av.push_back(p);
map<int,vector<Node*> > amap;
amap[0]=av;
while(true) {
vector<Node*> nodev;
for(int i=0;i<amap[level].size();i++) {
Node* an = amap[level][i];
cout << an->num << endl;
if (an->left!=NULL) {
nodev.push_back(an->left);
}
if (an->right!=NULL) {
nodev.push_back(an->right);
}
}
if (nodev.size()>0) {
amap[++level]=nodev;
}
else
break;
}
}
void print(Node* p) {
printtree(p,0);
}
Start traversing the tree after putting Root and new line in list. and then append new line whenever see new line in the list.
pseudo code:::
Tree *node=root;
list.push_back(node);
list.push_back(new_line_node);
while(node != null)
{
if (node->left != null)
list.push_back(node->left)
if (node->right != null)
list.push_back(node->right)
print (node->value)
if (list.pop_front == new_line_node)
{
print "\n"
list.push_back(new_line_node)
}
else
node=list.pop_front();
}
Couldn't we maintain a single queue and push every element in along with it's level number (which is level number of parent + 1). We also maintain a variable for the current level. Whenever the element popped out has a level number greater than the current level, we go to a new line and increment the current level number before continuing as before.
Couldn't we maintain a single queue and push the left and right children of each node popped out along as a new object with an associated level number (which is level number of parent + 1). We also maintain a variable for the current level. Whenever the element popped out has a level number greater than the current level, we go to a new line and increment the current level number before continuing as before.
- Zhengyang.Feng2011 March 08, 2012