Leetcode 102 Solution

This article provides solution to leetcode question 102 (binary-tree-level-order-traversal)

https://leetcode.com/problems/binary-tree-level-order-traversal

Solution

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        queue<TreeNode*> q;
        vector<vector<int>> res;

        if (root)
            q.push(root);

        while (q.empty() == false)
        {
            auto size = q.size();
            vector<int> v;

            for (int i = 0; i < size; i++)
            {
                auto p = q.front();
                q.pop();

                v.push_back(p->val);

                if (p->left)
                    q.push(p->left);
                if (p->right)
                    q.push(p->right);
            }

            res.push_back(v);
        }

        return res;
    }
};