Leetcode 107 Solution

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

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

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>> levelOrderBottom(TreeNode* root) {
        queue<TreeNode*> q;
        vector<vector<int>> res;

        q.push(root);

        while (q.empty() == false)
        {
            vector<TreeNode*> nodes;
            vector<int> v;

            while (q.empty() == false)
            {
                nodes.push_back(q.front());
                q.pop();
            }

            for (auto it = nodes.begin(); it != nodes.end(); it++)
            {
                if (*it == NULL)
                    continue;

                q.push((*it)->left);
                q.push((*it)->right);

                v.push_back((*it)->val);
            }

            if (v.empty() == false)
                res.push_back(v);
        }

        reverse(res.begin(), res.end());

        return res;
    }
};