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]
此题容易想到使用GFS方法遍历,使用两层while循环,第一层用来判断树的当前层是否有节点,第二层循环每次将队列中的也就是当前层的树节点找到最大值存入vector,并且将下一层的节点推入队列中,直到树的下一层没有节点退出循环。
class Solution {
public:
vector<int> largestValues(TreeNode* root) {
vector<int> res;
queue<TreeNode*> q;
if (root) q.push(root);
int curr = q.size();
while (curr) {
res.emplace_back(INT_MIN);
while (curr--) {
res.back() = max(res.back(), q.front()->val);
if (q.front()->left) q.push(q.front()->left);
if (q.front()->right) q.push(q.front()->right);
q.pop();
}
curr = q.size();
}
return res;
}
};