TREES Q1 LEVEL ORDER TRAVERSAL

PHOTO EMBED

Mon Nov 25 2024 19:16:39 GMT+0000 (Coordinated Universal Time)

Saved by @E23CSEU1151

// Online C++ compiler to run C++ program online
#include <iostream>
#include <vector>
#include <queue>

using namespace std ;

struct Node
{
    int data ;
    Node* left;
    Node* right;
    
    Node(int x){
        data = x;
        left = right = NULL; 
    }
}

vector <int> levelOrder(Node* root){
    vector<int> ans;
    if(!root) 
    {
        return ans; // means no root (base case )
    }
    
    queue<Node*> q ;
    q.push(root);
    while(!q.empty()){
        Node* t= q.front();
        ans.push_back(t->data);
        if(t->left) {
            q.push(t->left);
        }
        if(t->right) {
            q.push(t->right);
        }
        q.pop();
    }
    return ans;
    
}
content_copyCOPY