算法题目 : 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].
算法分析:
这道题让我们找二叉树每行的最大的结点值,那么实际上最直接的方法就是用层序遍历。用队列queue实现广度优先搜索,将i层的数存到队列中,并且在i+1层数字入队的过程中进行i层的比较,最终当所有都存完之后也就得到了以个最大的数。然后存入vector中并输出就好了。
算法代码(C++):
class Solution {
public:
vector<int> largestValues(TreeNode* root) {
if (!root) return {};
vector<int> res;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
int n = q.size(), mx = INT_MIN;
for (int i = 0; i < n; ++i) {
TreeNode *t = q.front(); q.pop();
mx = max(mx, t->val);
if (t->left) q.push(t->left);
if (t->right) q.push(t->right);
}
res.push_back(mx);
}
return res;
}
};