Level order traversal

Given a binary tree, find its level order traversal.
Level order traversal of a tree is breadth-first traversal for the tree.

Example 1:

Input:
    1
  /   \ 
 3     2
Output:1 3 2

Example 2:

Input:
        10
     /      \
    20       30
  /   \
 40   60
Output:10 20 30 40 60 N N

method:


c++ implementation:

vector<int> levelOrder(Node* node)
{  
   queue<Node*>q; vector<int>ve;
   q.push(node);
   
   while(!q.empty())
   {   
      Node*n=q.front();
      ve.push_back(n->data);
      q.pop();
      if(n->left!=NULL)
      q.push(n->left);
      if(n->right!=NULL)
      q.push(n->right);
   }
   return ve;
}


Time Complexity: O(n) 
space Complexity: O(n) 

No comments

darkmode