这道题目就是层序遍历,解题思路就是我们维护一个队列,和一个答案数组,每次从队列里面取出一个,将他的值放入数组,判断这个取出来的节点是否存在左右子节点,存在则放入队列中,循环的退出条件是,当队列为空。
vector<int>ans;
queue<TreeNode *>que;
if(root==NULL) return {};
que.push(root);
while(!que.empty())
{
auto temp=que.front();
que.pop();
ans.push_back(temp->val);
if(temp->left!=NULL)
{
que.push(temp->left);
}
if(temp->right!=NULL)
{
que.push(temp->right);
}
}
return ans;
}
这道题目作为上一道题的变形,我一开始还没想出方法,看到题解后,得出解法,我们只需每次在判断队列非空是在循环里面先求出队列的长度,然后在里面再做循环,只有根节点在队列弹出式,size=1,循环一次,然后弹出,此时根节点的两个子节点进入队列,size=2,所以再创建一个vector,每次将此次循环的节点放入,循环结束后,再插入答案数组即可。
vector<vector<int>>ans;
queue<TreeNode *>que;
if(root==NULL) return {};
que.push(root);
while(!que.empty())
{
vector<int>path;
int size=que.size();
for(int i=0;i<size;i++)
{
auto temp=que.front();
que.pop();
path.push_back(temp->val);
if(temp->left!=NULL)
{
que.push(temp->left);
}
if(temp->right!=NULL)
{
que.push(temp->right);
}
}
ans.push_back(path);
}
return ans;
只是第二题的变形,我们只需要设置一个计数器就可以了
注意vector<int>(path.rbegin(),path.rend())比较reverse(path.begin(),path.end());的写法更快
vector<vector<int>>ans;
queue<TreeNode *>que;
if(root==NULL) return {};
que.push(root);
int count =1;
while(!que.empty())
{
vector<int>path;
int size=que.size();
for(int i=0;i<size;i++)
{
auto temp=que.front();
que.pop();
path.push_back(temp->val);
if(temp->left!=NULL)
{
que.push(temp->left);
}
if(temp->right!=NULL)
{
que.push(temp->right);
}
}
if((count %2) ==1)
{
ans.push_back(path);
count++;
}
else
{
ans.push_back(vector<int>(path.rbegin(),path.rend()));
count++;
}
}
return ans;
}
奇偶层的打印顺序不一样是相反的,可以利用层数偶数与否调用reverse来解决,但是海量数据时这个效率很低,不推荐。
因为奇数层的打印顺序是从左到右,偶数层的打印顺序是从右到左,可以利用STL容器deque中
push_back(),push_front(),front(),back(),pop(),popfront()来实现
前取后放,后取前放!!,同时注意往前放的时候要记得,将左右节点从前面放的顺序和从后面放的顺序要反过来,要保证进去后队列始终是有序的
vector<vector<int>>ans;
deque<TreeNode *>que;
if(root==NULL) return {};
que.push_back(root);
int count =1;
while(!que.empty())
{
vector<int>path;
int size=que.size();
for(int i=0;i<size;i++)
{
if(count %2==1)
{
auto temp=que.front();
que.pop_front();
path.push_back(temp->val);
if(temp->left!=NULL) que.push_back(temp->left);
if(temp->right!=NULL) que.push_back(temp->right);
}
else
{
auto temp=que.back();
que.pop_back();
path.push_back(temp->val);
if(temp->right!=NULL) que.push_front(temp->right);//这里要顺序反一下右先进去
if(temp->left!=NULL) que.push_front(temp->left);
}
}
ans.push_back(path);
count++;
}
return ans;