一開始沒有考慮每層中會出現負數的情況,之後把負無窮取爲 -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;
}
};