Level order traversal Line by Line | Practice | GeeksforGeeks

Given a Binary Tree, your task is to find its level order traversal.
For the below tree the output will be 1 $ 2 3 $ 4 5 6 7 $ 8 $.
          1
       /     \
     2        3
   /    \     /   \
  4     5   6    7
    \
     8
Example 1:
Input:
          1
        /
       4
     /   \
    4     2
Output:1 $ 4 $ 4 2 $


Example 2:
Input:
            10
          /    \
        20      30
     /     \
    40     60
Output: 10 $ 20 30 $ 40 60 $

Your Task:
This is a function problem. You don't need to read input. Just complete the function levelOrder() that takes nodes as parameter and returns level order traversal as a 2D list.
Note: The driver code prints the levels '$' separated.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 <= Number of edges <= 1000
0 <= Data of a node <= 100
+1
rayalravi20011 week ago
c++ solution 
 
vector<vector<int>> res; if(!root){     return res; } queue<Node*> q; q.push(root); while(!q.empty()){     int size = q.size();     vector<int> inner;     while(size--){       Node *curr = q.front();       q.pop();       inner.push_back(curr->data);       if(curr->left)          q.push(curr->left);       if(curr->right)         q.push(curr->right);     }     res.push_back(inner); } return res;
0
itachinamikaze2211 week ago
static ArrayList<ArrayList<Integer>> levelOrder(Node root)    {       Queue<Node> que= new LinkedList<Node>();       ArrayList<ArrayList<Integer>> res= new ArrayList<ArrayList<Integer>>();       if(root==null)           return res;              que.offer(root);       while(!que.isEmpty())       {           int levelNum = que.size();           ArrayList<Integer> subres= new ArrayList<Integer>();           for(int i=1; i<=levelNum; i++)           {               if(que.peek().left!=null)                   que.offer(que.peek().left);               if(que.peek().right!=null)                   que.offer(que.peek().right);               subres.add(que.poll().data);           }           res.add(subres);       }       return res;   }
0
crawler1 month ago
vector<vector<int>> levelOrder(Node* node)
{
    queue<Node *> values;
    vector<vector<int>> result;
    values.push(node);
    while(!values.empty()){
        vector<int> result2;
        queue<Node *> childs;
        while(!values.empty()){
            Node *temp = values.front();
            result2.push_back(temp->data);
            values.pop();
            if(temp->left)
                childs.push(temp->left);
            if(temp->right)
                childs.push(temp->right);
        }
        result.push_back(result2);
        values = childs;
        while(!childs.empty())
            childs.pop();
    }
    return result;
}
0
ruchitchudasama1232 months ago
vector<vector<int>> levelOrder(Node* node){ vector<vector<int>> ans; vector<int> res; queue<Node*> q; q.push(node);//   q.push(NULL);   while(!q.empty()){       int size=q.size();       for(int i=0;i<size;i++){           Node* cur=q.front();           q.pop();           if(cur->left){               q.push(cur->left);           }           if(cur->right){               q.push(cur->right);           }           res.push_back(cur->data);       }       ans.push_back(res);       res.clear();   }   return ans;}
0
detroix072 months ago
vector<vector<int>> levelOrder(Node* root){    vector<vector<int>> ans;    vector<int> v;        queue<Node*> q;    q.push(root);    q.push(NULL);        while(q.size()!=0){     Node* temp = q.front();     if(temp==NULL){       ans.push_back(v);       v.clear();       q.pop();       if(q.size()==0){        break;       } else {         q.push(NULL);       }     } else {       v.push_back(temp->data);       if(temp->left) q.push(temp->left);       if(temp->right) q.push(temp->right);       q.pop();     }    }    return ans;    }
 
+1
baibhavrajputt3 months ago
Java solution
class Level_Order_Traverse
{
    //Function to return the level order traversal line by line of a tree.
    static ArrayList<ArrayList<Integer>> levelOrder(Node node) 
    {
        // Your code here
        ArrayList<ArrayList<Integer>> outer = new ArrayList<ArrayList<Integer>>();
        if(node == null)
            return outer;
            
        Queue<Node> q = new LinkedList<>();
        q.add(node);
        
        int currLen = 0;
        while(q.isEmpty() == false){
            ArrayList<Integer> inner = new ArrayList<>();
            currLen = q.size();
            
            for(int i=0 ; i<currLen ; i++){
                Node curr = q.poll();
                inner.add(curr.data);
                
                if(curr.left != null){
                    q.add(curr.left);
                }
                if(curr.right != null){
                    q.add(curr.right);
                }
            }
            outer.add(inner);
        }
        return outer;
    }
}
0
vadapaav3 months ago
What's wrong with this code ?? Please help
 
vector<vector<int>> levelOrder(Node* root){   vector<vector<int>> res;   vector<int> sub;   queue<Node*> q;   q.push(root);   q.push(NULL);   while(q.size()>1) {       Node *curr = q.front();       q.pop();       if(curr==NULL) {           res.push_back(sub);           sub.clear();           q.push(NULL);           continue;       }       sub.push_back(curr->data);       if(curr->left!=NULL)           q.push(root->left);       if(curr->right!=NULL)           q.push(root->right);   }   return res;}
+1
aniketkumar53 months ago
 public static  Queue<Node> q = new ArrayDeque<Node>();   static ArrayList<ArrayList<Integer>> levelOrder(Node node)    {       // Your code here       ArrayList<ArrayList<Integer>> al1=new ArrayList<ArrayList<Integer>>();       if(node==null){          return al1;      }        q.offer(node);      while(q.isEmpty()==false){          int n=q.size();              ArrayList<Integer> al2=new ArrayList<Integer>();              for(int i=0;i<n;i++){              Node curr=q.poll();              al2.add(curr.data);              if(curr.left!=null)  q.offer(curr.left);              if(curr.right!=null) q.offer(curr.right);              }           al1.add(al2);      }             return al1;   }
+2
sohamdas86973 months ago
queue <Node*> q;
    q.push(node);
    vector <vector <int>> v;
    while(!q.empty()) {
        int n = q.size();
        vector <int> level;
        for(int i=0; i<n; i++) {
            auto temp = q.front();
            q.pop();
            if(temp->left) 
                q.push(temp->left);
            if(temp->right)
                q.push(temp->right);
            level.push_back(temp->data);
        }
        v.push_back(level);
    }
    return v;
0
ketankumar14 months ago
vector<vector<int>> levelOrder(Node* node)
{
  //Your code here
  if(!node) return {{}};
  
  vector<vector<int>> res;
  queue<Node*> q;
  q.push(node);
  
  while(!q.empty()) {
      int n = q.size();
      Node* curr;
      vector<int> temp;
      
      for(int i = 0; i < n ; ++i) {
          curr = q.front();
          temp.push_back(curr->data);
          if(curr->left) q.push(curr->left);
          if(curr->right) q.push(curr->right);
          q.pop();
      }
      
      res.push_back(temp);
  }
  return res;
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.