515. Find Largest Value in Each Tree Row
You need to find the largest value in each row of a binary tree.
Example:
Input: 1 / \ 3 2 / \ \ 5 3 9 Output: [1, 3, 9]
标准BFS。
/**
* 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)
{
queue<TreeNode*> que;
if (root) que.push(root);
vector<int> ret;
while (!que.empty())
{
int size = que.size();
int maxv = INT_MIN;
for (int i = 0; i < size; i++)
{
TreeNode* tmp = que.front();
maxv = max(maxv, tmp->val);
que.pop();
if (tmp->left)
que.push(tmp->left);
if (tmp->right)
que.push(tmp->right);
}
ret.push_back(maxv);
}
return ret;
}
};