【牛客题霸题解】二叉树的之字形层序遍历（待更新）

http://www.nowcoder.com/practice/47e1687126fa461e8a3aff8632aa5559

/**
* struct TreeNode {
*    int val;
*    struct TreeNode *left;
*    struct TreeNode *right;
* };
*/
struct node{
int index;
TreeNode *root;
};
#include<queue>
class Solution {
public:
/**
* @param root TreeNode类
* @return int整型vector<vector<>>
*/
vector<vector<int> > zigzagLevelOrder(TreeNode* root) {
// write code here
vector<vector<int> > t;
if(root==NULL)return t;
queue <node>  Q;
vector<node>  save;
Q.push(node{0,root});
while(!Q.empty())
{
node top=Q.front();
Q.pop();
save.push_back(top);
if(top.root->left != NULL){Q.push(node{top.index+1,top.root->left});}
if(top.root->right != NULL){Q.push(node{top.index+1,top.root->right});}
}
int num = save.size();
// cout<<num;
vector<vector<int> > ans(save[num-1].index+1);
for(int i = 0 ; i < num ; i++)
{
ans[save[i].index].push_back(save[i].root->val);
}
for(int i = 1 ; i < save[num-1].index+1 ; i+=2)
{
reverse(ans[i].begin(),ans[i].end());
}
return ans;
}
};

QAQ

2022-12-22 18:27

2022-12-14 16:44

2022-12-12 11:15

2022-12-22 15:22

2022-12-24 07:19

2022-12-30 21:00

2022-12-19 16:29

2022-12-16 16:59

2022-12-23 19:23

2022-12-08 09:51

2022-12-14 17:42