Description
You need to find the largest value in each row of a binary tree.
Example:
Difficluty:Medium
Thinking
典型的广度优先搜索算法题。用BFS遍历树,再用一个数组记录每一行的最大值即可。for循环遍历一层的条件是 i < size,size是下层子节点push进队列前的queue.size();
Solution
/**
* 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) return {};
vector<int> maxv;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
int max = INT_MIN;
int size = q.size();
for(int i = 0; i < size; i++){
TreeNode* temp = q.front();
q.pop();
if(max < temp->val) max = temp->val;
if(temp->left) q.push(temp->left);
if(temp->right) q.push(temp->right);
}
maxv.push_back(max);
}
return maxv;
}
};