当前位置:网站首页>LeetCode-515. Find the maximum value in each tree row

LeetCode-515. Find the maximum value in each tree row

2022-06-27 05:17:00 Border wanderer

Given the root node of a binary tree  root , Please find the maximum value of each layer in the binary tree .

Example 1:

Input : root = [1,3,2,5,3,null,9]
Output : [1,3,9]
Example 2:

Input : root = [1,2,3]
Output : [1,3]
 

Tips :

The range of the number of nodes in a binary tree is [0,104]
-231 <= Node.val <= 231 - 1
 

#include<iostream>
#include<vector>
#include<queue>
using namespace std;
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) {
        if (!root) {
            return {};
        }
        vector<int> res;
        queue<TreeNode*> q;
        q.push(root);
        while (!q.empty()) {
            int len = q.size();
            int maxVal = INT_MIN;
            while (len--) {
                TreeNode* t = q.front();
                q.pop();
                maxVal = maxVal > t->val ? maxVal : t->val;
                if (t->left) {
                    q.push(t->left);
                }
                if (t->right) {
                    q.push(t->right);
                }
            }

            res.push_back(maxVal);
        }
        return res;
    }

};
原网站

版权声明
本文为[Border wanderer]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/178/202206270514234496.html