Avatar of ODOTServer
ODOTServer
Flag for United States of America

asked on 

How to print a level order traversal

I would like to print nodes and level using the level order traversal method.

I have the code to print each node in level order but I do not know how to assign the level of the tree with each node such that cout<<sub_root->data<<" "<<level;

Would it be best to have a helper function to pass nodes to from the queue and print that way?
If so, how would I implement it? Thanks.
void AVL_tree<Record>::level_order() {
 
	queue<Binary_node<Record>*> Q;
 
	Q.push(root); //get root in queue
	
	while(Q.size() > 0)
	{
		
		Binary_node<Record> * sub_root = Q.front();
		cout<<sub_root->data<<" "<<endl;
         Q.pop();  //pop sub_root
		
		if(sub_root->left)
			Q.push(sub_root->left);  
		
		if(sub_root->right)
			Q.push(sub_root->right);
	}
}

Open in new window

C++

Avatar of undefined
Last Comment
Infinity08

8/22/2022 - Mon