学习安排根据《代码随想录》leetcode 107 leetcode199 leetcode639
107
上个练习 最后加一个 reverse 就行了
reverse(v.begin(),v.end());
199
思路:只输出 每层的最后一个元素!!!!!!!
/**
* 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> rightSideView(TreeNode* root)
{
queue<TreeNode*> que;
if (root != NULL) que.push(root);
vector<int>vec;
while (!que.empty()) {
int size = que.size();
// 这里一定要使用固定大小size,不要使用que.size(),因为que.size是不断变化的
for (int i = 0; i < size; i++) {
TreeNode* newNode = que.front();
que.pop();
if(i==size-1)
vec.push_back(newNode->val);
if(newNode->left)que.push(newNode->left);
if(newNode->right)que.push(newNode->right);
}
}
return vec;
}
};
639
可恶,又被简单题摆了一道!局部变量没有设置好,导致输出结果一直不对![○・`Д´・ ○]
/**
* 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<double> averageOfLevels(TreeNode* root)
{
vector<double>vec;
queue<TreeNode*>q;
q.push(root);
double sum;
while(!q.empty())
{
int size=q.size();
sum=0;//局部变量设置在 for 外面 ,防止每一层在遍历时,sum一直从0开始
for(int i=0;i<size;i++)
{
TreeNode*newNode=q.front();
q.pop();
sum+=newNode->val;
if(newNode->left) q.push(newNode->left);
if(newNode->right) q.push(newNode->right);
}
vec.push_back(sum/size);
}
return vec;
}
};