题目
您需要在二叉树的每一行中找到最大的值。
示例:
输入:
1
/ \
3 2
/ \ \
5 3 9
输出: [1, 3, 9]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-largest-value-in-each-tree-row
解题思路
还是简单的层序遍历
代码(C++)
/**
* 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) {
if(root==NULL) return {};
queue<TreeNode*> q;
q.push(root);
vector<int> res;
while(!q.empty()){
int qsz=q.size();
int qmax=INT_MIN;
for(int i=0;i<qsz;++i){
TreeNode* tmp=q.front();
q.pop();
qmax=max(qmax,tmp->val);
if(tmp->left) q.push(tmp->left);
if(tmp->right) q.push(tmp->right);
}
res.push_back(qmax);
}
return res;
}
};