C++ BFS Solution


  • 0
    S
    class Solution {
    public:
        vector<vector<int>> levelOrder(TreeNode* root) {
            vector<vector<int>> ret;
            if ( root == nullptr ) return ret;
    
            queue<TreeNode*> samelevel;
            samelevel.push(root);
            vector<int> row;
            while(!samelevel.empty()) {
                int size = samelevel.size();
                for ( int i = 0; i < size; i++ ) {
                    TreeNode* cur = samelevel.front();
                    samelevel.pop();
                    row.push_back(cur->val);
                    if(cur->left != nullptr) samelevel.push(cur->left);
                    if(cur->right != nullptr) samelevel.push(cur->right);
                }
                ret.push_back(row);
                row.clear();
            }
            return ret;
        }
    };
    

Log in to reply
 

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