vector<vector<int>> levelOrder(TreeNode* root)
{
vector<vector<int>> ret;
vector<int> oneLayer;
if (root == nullptr) {
return ret;
}
queue<TreeNode*> q;
q.emplace(root);
int len = 1;
int cur = 0;
int s = 0;
while (!q.empty()) {
oneLayer.clear();
s = 0;
while (cur < len) {
TreeNode* tmp = q.front();
oneLayer.push_back(tmp->val);
q.pop();
if (tmp->left != nullptr) {
q.push(tmp->left);
s++;
}
if (tmp->right != nullptr) {
q.push(tmp->right);
s++;
}
cur++;
}
ret.push_back(oneLayer);
len = s;
cur = 0;
}
return ret;
}
107. 二叉树的层序遍历 II - 力扣(LeetCode)
vector<vector<int>> levelOrder(TreeNode* root)
{
vector<vector<int>> ret;
vector<int> oneLayer;
if (root == nullptr) {
return ret;
}
queue<TreeNode*> q;
q.emplace(root);
int len = 1;
int cur = 0;
int s = 0;
while (!q.empty()) {
oneLayer.clear();
s = 0;
while (cur < len) {
TreeNode* tmp = q.front();
oneLayer.push_back(tmp->val);
q.pop();
if (tmp->left != nullptr) {
q.push(tmp->left);
s++;
}
if (tmp->right != nullptr) {
q.push(tmp->right);
s++;
}
cur++;
}
ret.push_back(oneLayer);
len = s;
cur = 0;
}
std::reverse(ret.begin(), ret.end());
return ret;
}
vector<double> averageOfLevels(TreeNode* root)
{
vector<double> ret;
queue<TreeNode*> q;
if (root == nullptr) {
return ret;
}
int cur = 0;
int curLayerSize = 1;
int nextLayerSize = 0;
while (!q.empty()) {
double sum = 0.0;
while (cur < curLayerSize) {
TreeNode* node = q.front();
q.pop();
sum += node->val;
if (node->left != nullptr) {
q.push(node->left);
nextLayerSize++;
}
if (node->right != nullptr) {
q.push(node->right);
nextLayerSize++;
}
cur++;
if (cur == curLayerSize) {
ret.push_back(sum / curLayerSize);
}
}
curLayerSize = nextLayerSize;
nextLayerSize = 0;
cur = 0;
}
return ret;
}
vector<int> rightSideView(TreeNode* root)
{
vector<int> ret;
if (root == nullptr) {
return ret;
}
queue<TreeNode*> q;
q.emplace(root);
int len = 1;
int cur = 0;
int s = 0;
while (!q.empty()) {
s = 0;
while (cur < len) {
TreeNode* tmp = q.front();
q.pop();
if (tmp->left != nullptr) {
q.push(tmp->left);
s++;
}
if (tmp->right != nullptr) {
q.push(tmp->right);
s++;
}
if (cur == len - 1) {
ret.push_back(tmp->val);
}
cur++;
}
len = s;
cur = 0;
}
return ret;
}