Reputation: 125
I am wondering how to find out the level where each node is. But I can't figure it out.
Here is the part of the section of the code, but I have to modify it.
if(root == NULL)
return;
q.enqueue(root);
while(!queue.empty()){
queue.dequeue(cur);
if( cur != NULL){
cout<<cur->data<<" ";
if(cur->left != NULL)
queue.enqueue(cur->left);
if(cur->right != NULL)
queue.enqueue(cur->right);
}
}
How to modify the code, so that I can know the level of each node ? Hope you guys can give me some algorithms about this question.
Upvotes: 0
Views: 225
Reputation: 54074
You are doing level order traversal which is in the correct direction. If you need to print which level you are at:
if(root == NULL)
return;
int level = 1;
q.enqueue(root);
q.enqueue(NULL);
while(!queue.empty()){
queue.dequeue(cur);
if(cur == NULL){
//going to next level
level++;
if(queue.empty()){
break;
}
queue.enqueue(NULL);
}
else {
cout << "LEVEL is: " << level;
cout<<cur->data<<" ";
if(cur->left != NULL){
queue.enqueue(cur->left);
}
if(cur->right != NULL){
queue.enqueue(cur->right);
}
}
}
Upvotes: 2