链接: leetcode515. 在每个树行中找最大值
描述,示例和提示:
class Solution {
public:
vector largestValues(TreeNode* root) {
if(!root) return {};
queue q;
vector ret;
q.push(root);
while(!q.empty())
{
int len = q.size();
int rets = INT_MIN;
while(len>0)
{
len--;
auto it = q.front();
q.pop();
rets = max(rets, it->val);
if(it->left) q.push(it->left);
if(it->right) q.push(it->right);
}
ret.push_back(rets);
}
return ret;
}
};
题目解析:
二叉树的题基本都是遍历问题,只要找到合适的遍历方法即可,
本题运用了层序遍历的非递归式方法
每一层节点插入到队列的时候,顺便判断一下这一层的最大值即可。
链接: 层序遍历:



