515.在每个树行中找最大值
链接:515.在每个树行中找最大值
难度:Medium
标签:树、深度优先搜索、广度优先搜索、二叉树
简介:给定一棵二叉树的根节点 root ,请找出该二叉树中每一层的最大值。
题解 1 - cpp
- 编辑时间:2022-06-24
- 执行用时:8ms
- 内存消耗:21.6MB
- 编程语言:cpp
- 解法介绍:层序遍历。
class Solution {
   public:
    vector<int> largestValues(TreeNode* root) {
        vector<int> ans;
        if (root == nullptr) return ans;
        queue<TreeNode*> q;
        q.push(root);
        ans.push_back(root->val);
        int size = 1, nmax = INT_MIN;
        while (q.size()) {
            TreeNode* node = q.front();
            q.pop();
            if (node->left) {
                q.push(node->left);
                nmax = max(nmax, node->left->val);
            }
            if (node->right) {
                q.push(node->right);
                nmax = max(nmax, node->right->val);
            }
            if (--size == 0) {
                if (q.size()) ans.push_back(nmax);
                nmax = INT_MIN;
                size = q.size();
            }
        }
        return ans;
    }
};