题目链接:https://leetcode-cn.com/problems/find-largest-value-in-each-tree-row/
题目描述
您需要在二叉树的每一行中找到最大的值。
示例:
输入:
1
/ \
3 2
/ \ \
5 3 9
输出: [1, 3, 9]
思路
层次遍历
代码
// 层次遍历
class Solution {
public:
vector<int> largestValues(TreeNode* root) {
vector<int> ret;
if(!root) return ret;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
int cnt = q.size();
int maxVal = INT_MIN;
while(cnt--){
root = q.front();
q.pop();
maxVal = max(maxVal, root->val);
if(root->left)
q.push(root->left);
if(root->right)
q.push(root->right);
}
ret.push_back(maxVal);
}
return ret;
}
};