Level Traversal
Define the type for binary trees.
template <typename T> struct BinaryNode{
T elem;
BinaryNode *left;
BinaryNode * right;
BinaryNode(T d, BinaryNode *l=NULL, BinaryNode *r=NULL):elem(d),left(l),right(r){};
};
Your task is to implement the level traversal of binary trees.
template <typename T>
void levelTraversal(BinaryNode<T>* root, void (*visit)(T &x))
template <typename T>
void levelTraversal(BinaryNode<T>* root, void (*visit)(T &x)){
if(root == NULL) return;
queue<BinaryNode<T>*> Q;
Q.push(root);
//while there is at least one discovered node
while(!Q.empty()) {
BinaryNode<T>* current = Q.front();
Q.pop(); // removing the element at front
(*visit)(current->elem);
if(current->left != NULL) Q.push(current->left);
if(current->right != NULL) Q.push(current->right);
}
}