题目
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) {
if (!root) return {};
queue<TreeNode*> q;
q.push(root);
int res;
std::vector<int> v;
TreeNode *cur = root;
while (!q.empty()) {
int n = q.size();
res = INT_MIN;
while (n--) {
cur = q.front();
if (cur->left) q.push(cur->left);
if (cur->right) q.push(cur->right);
if (cur->val > res) res = cur->val;
q.pop();
}
v.push_back(res);
}
return v;
}
};