C++ 6ms solution


  • 0

    My C++ one queue 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) {
            vector<vector<int>> rst;
            queue<TreeNode*> q;
            q.push(root);
            q.push(NULL);
            while (q.front()){
                vector<int> layer;
                while (q.front()){
                    TreeNode* cur = q.front();
                    layer.push_back(cur->val);
                    q.pop();
                    if (cur->left) q.push(cur->left);
                    if (cur->right) q.push(cur->right);
                }
                rst.push_back(layer);
                q.pop();
                q.push(NULL);
            }
            reverse(rst.begin(),rst.end());;
            return rst;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.