一开始没有考虑每层中会出现负数的情况,之后把负无穷取为 -0x3f3f3f3f,以为已经足够小了。结果有个测试用例居然是这样的:
...... 最后老老实实换成INT_MIN吧。
思路:
树的层次遍历,也就是图的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==NULL)
return {};
vector<int> ans;
queue<TreeNode*> q;
q.push(root);
TreeNode* cur=NULL;
int nodesCnt=q.size();//每一层的节点数
int layer_max=INT_MIN;//每一层的最大值
while(!q.empty()){
cur=q.front();
q.pop();
if(cur->left)
q.push(cur->left);
if(cur->right)
q.push(cur->right);
layer_max=(layer_max>cur->val)? layer_max:cur->val;
if(--nodesCnt==0){//当前层全部弹出时
ans.push_back(layer_max);
nodesCnt=q.size();
layer_max=INT_MIN;
}
}
return ans;
}
};