Concise C++ BFS Solution


  • -1
    class Solution {
    public:
        vector<int> largestValues(TreeNode* root) {
            vector<int> res;
            queue<TreeNode*> q;
            if (root) q.push(root);
            int curr = q.size();
            while (curr) {
                res.emplace_back(INT_MIN);
                while (curr--) {
                    res.back() = max(res.back(), q.front()->val);
                    if (q.front()->left)  q.push(q.front()->left);
                    if (q.front()->right) q.push(q.front()->right);
                    q.pop();
                }
                curr = q.size();
            }
            
            return res;
        }
    };
    

Log in to reply
 

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