BFS C++ solution


  • 0
    W
    class Solution {
    public:
        vector<int> largestValues(TreeNode* root) {
            if(!root) return vector<int>();
            vector<int> res;
            queue<TreeNode*> q;
            q.push(root);
            while(!q.empty()) {
                int largest = INT_MIN, n = q.size();
                for(int i = 0; i < n; i++) {
                    TreeNode* cur = q.front();
                    q.pop();
                    largest = max(largest, cur->val);
                    if(cur->left) q.push(cur->left);
                    if(cur->right) q.push(cur->right);
                }
                res.push_back(largest);
            }
            return res;
        }
    };
    

Log in to reply
 

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