Problem: Write a method to print level order traversal of a binary tree.
Approach: Use queue.
Implementation in C++:
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