Tuesday, May 5, 2015

Level order traversal of a binary tree

Problem: Write a method to print level order traversal of a binary tree.

Approach: Use queue.

Implementation:

void BSTree::levelOrder()
{
if(!root)
return;
std::queue<Node*> nodesQ;
nodesQ.push(root);
while(!nodesQ.empty())
{
Node* temp = nodesQ.front();
std::cout<<temp->data<<'\t';
if(temp->left)
nodesQ.push(temp->left);
if(temp->right)
nodesQ.push(temp->right);
nodesQ.pop();
}
}

Complexity: O(n)

No comments:

Post a Comment