C++ solution using BFS + Stack, optimised using std::move (faster than 95% of submissions)


  • 2
    C
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        vector<vector<int>> result;
        if (root == NULL) return result;
        stack<vector<int>> level_tmp;
        queue<TreeNode*> q;
        q.push(root);
        while (!q.empty()) {
            vector<int> level;
            size_t size = q.size();
            for (int i = 0; i < size; ++i) {
                TreeNode* node = q.front(); q.pop();
                level.push_back(node->val);
                if (node->left != NULL) q.push(node->left);
                if (node->right != NULL) q.push(node->right);
            }
            level_tmp.emplace(move(level));
        }
        while (!level_tmp.empty()) {
            result.emplace_back(move(level_tmp.top()));
            level_tmp.pop();
        }
        return vector<vector<int>>(result);
    }

Log in to reply
 

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