/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> largestValues(TreeNode* root) {
queue<TreeNode*>q;
if(root)q.push(root);
vector<int>ans;
while(!q.empty()){
int k=q.size();
int cnt=q.front()->val;
while(k--){
TreeNode*p=q.front();
if(p->left)q.push(p->left);
if(p->right)q.push(p->right);
if(cnt<p->val)cnt=p->val;
q.pop();
}
ans.push_back(cnt);
}
return ans;
}
};
515. 在每个树行中找最大值
这篇文章介绍了一个名为Solution的类,其中包含一个largestValues函数,使用广度优先搜索(BFS)策略在给定的二叉树中找到每个节点的最大值路径。函数通过维护队列来遍历树并更新最大值。
摘要由CSDN通过智能技术生成