程式語言 - LeetCode - C++ - 515. Find Largest Value in Each Tree Row



題目:


解答:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> largestValues(TreeNode* root) {
        vector<int> ans;
        queue<TreeNode*> q;

        if (!root) {
            return ans;
        }

        q.push(root);
        while (!q.empty()) {
            long mx = LONG_MIN;
            int size = q.size();

            for (int i = 0; i < size; ++i) {
                TreeNode* t = q.front();
                q.pop();

                mx = max(mx, static_cast<long>(t->val));
                if (t->right) {
                    q.push(t->right);
                }
                if (t->left) {
                    q.push(t->left);
                }
            }

            ans.push_back(mx);
        }

        return ans;
    }
};