4.Level-order Traversal

Traversing Level by level

Level-order traversal is to traverse the tree level by level.

Level order traversal using queue

class Solution
{
public:
    vector<vector<int>> levelOrder(TreeNode *root)
    {
        vector<vector<int>> vect;
        if (root == NULL)
        {
            return vect;
        }
        queue<TreeNode *> q;
        TreeNode *t = NULL;
        q.push(root);
        vector<int> v;

        while (!q.empty())
        {
            int s = q.size();
             vector<int> v;
            while (s > 0)
            {
                t = q.front();
                q.pop();
                v.push_back(t->val);
                
                if (t->left)
                {
                    q.push(t->left);
                }
                if (t->right)
                {
                    q.push(t->right);
                }
                s--;
            }
            if(v.size()!=0){
              vect.push_back(v);
            }
        }
        return vect;
    }
};

Last updated