Tree: Level Order Traversal

  • + 0 comments

    My C++ Solution:

    void levelOrder(Node * root) {
            queue<Node*> q;
            if(root == NULL)return;
            q.push(root); // add root to queue
            while(!q.empty()){
                for(int i=0; i<q.size(); i++){
                    Node* tempN = q.front();
                    cout << tempN->data << " "; // if you want to store you can do push_back here
                    q.pop();
                    if(tempN->left != NULL)q.push(tempN->left);
                    if(tempN->right != NULL)q.push(tempN->right);
                }
            }
        }