目录
💎一、题目
🏆1.题目描述
🏆2.原题链接
💎二、解题报告
🏆1.思路分析
🔑思路:
和上一题的区别是,奇数行顺序存放,偶数行逆序粗放
🏆2.代码详解
/**
* 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<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> arr;
if(!root) return arr;
queue<TreeNode*> q;
q.push(root);
bool res = true; //1
while(q.size())
{
vector<int> v;
int size = q.size();
while(size) //2
{
TreeNode* tmp = q.front();
q.pop();
v.push_back(tmp->val);
if(tmp->left)
q.push(tmp->left);
if(tmp->right)
q.push(tmp->right);
--size;
}
if(res)
arr.push_back(v);
else
{
vector<int> vv (v.rbegin(), v.rend());
arr.push_back(vv);
}
res = !res;
}
return arr;
}
};
1.控制奇偶顺序
2.记录每一行剩余未存放的数据个数