LeetCode - 二叉树每层的最大值

https://leetcode.cn/problems/hPov7L/

    vector<int> largestValues(TreeNode* root) {
        if (root == nullptr)
            return {};

        vector<int> res;
        queue<TreeNode*> q;
        q.push(root);

        while(!q.empty())
        {
            int s = q.size();
            int max = INT_MIN;
            for(int i=0; i<s; ++i)
            {
                auto tmp = q.front();
                if (tmp->left) q.push(tmp->left);
                if (tmp->right) q.push(tmp->right);
                max = tmp->val > max ? tmp->val : max;
                q.pop();
            }
            res.push_back(max);
        }

        return res;
    }

你可能感兴趣的:(leetcode,leetcode,算法)