C++ BFS with NULL as a row marker


  • 0
    D
    /* The idea is to use a NULL as a row marker */
    class Solution {
    public:
        vector<int> largestValues(TreeNode* root) {
            if (!root) return {};
            vector<int> res;
            queue<TreeNode*> q;
            q.push(root);
            q.push(NULL);
            int max=INT_MIN;
            while (q.size()!=1) {
                TreeNode *t=q.front(); q.pop();
                if (!t){
                    res.push_back(max);
                    max=INT_MIN;
                    q.push(NULL);
                    continue;
                } else if (t->val > max)
                    max=t->val;
                if (t->left) q.push(t->left);
                if (t->right) q.push(t->right);
            }
            res.push_back(max);
            return res;
        }
    };
    

Log in to reply
 

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