515. 在每个树行中找最大值
您需要在二叉树的每一行中找到最大的值。
示例:
输入:
1
/ \
3 2
/ \ \
5 3 9
输出: [1, 3, 9]
解题思路: 这题属于层序遍历的应用,直接模板解题即可。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> largestValues(TreeNode* root) {
vector<int> res;
if (!root) return res;
queue<TreeNode*> q{{root}};
while (!q.empty()) {
int mx = INT_MIN;
for (int i = q.size(); i > 0; --i) {
TreeNode* t = q.front(); q.pop();
mx = max(mx, t->val);
if (t->left) q.push(t->left);
if (t->right) q.push(t->right);
}
res.push_back(mx);
}
return res;
}
};