C++, BFS, queue, use a nullptr as the separation of different levels


  • 0
    1
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        vector<vector<int>> result,reverse;
        if(!root) return result;
        queue<TreeNode*> que;
        TreeNode* flag=NULL;
        que.push(root);
        que.push(flag);
        vector<int> level;
        while(!que.empty()){
            auto ptr=que.front();
            que.pop();
            if(!ptr){
                if(que.empty()){
                    result.push_back(level);
                }
                else{
                    result.push_back(level);
                    level.clear();
                    que.push(ptr);
                }
            }
            else{
                level.push_back(ptr->val);
                if(ptr->left)
                   que.push(ptr->left);
                if(ptr->right)
                   que.push(ptr->right);
            }
        }
        int size=result.size();
        for(int i=0;i<size;++i){
            reverse.push_back(result.back());
            result.pop_back();
        }
        return reverse;
    }

Log in to reply
 

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