Share my iterative C++ solution,easy to understand


  • 1
    V
    class Solution {
    public:
        vector<vector<int>> levelOrderBottom(TreeNode* root) {
            vector<vector<int>> ret;
            if (root == NULL) return ret;
            
            TreeNode *temp = NULL;
            int curLevelCount = 0;
            
            queue<TreeNode *>q;
            q.push(root);
            
            while (!q.empty())
            {
                curLevelCount = q.size();
                vector<int> level;
                while (curLevelCount--)
                {
                    temp = q.front();
                    level.push_back(temp->val);
                    if (temp->left != NULL)
                        q.push(temp->left);
                    if (temp->right != NULL)
                        q.push(temp->right);
                    q.pop();
                }
                ret.insert(ret.begin(), level);
            }
            
            return ret;
        }
    };

Log in to reply
 

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