题解 | #按之字形顺序打印二叉树(队列)#
按之字形顺序打印二叉树
https://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * }; */ class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param pRoot TreeNode类 * @return int整型vector<vector<>> */ vector<vector<int> > Print(TreeNode* root) { vector<vector<int>> res; bool evenflag = true; //偶层数标志 queue<TreeNode*> q; q.push(root); if(root == nullptr) return res; while (!q.empty()) { int number = q.size(); //每层结点个数 vector<int> cur; for (int i = 0; i < number; i++) { TreeNode* node = q.front(); int value = node->val; cur.push_back(value); q.pop(); if (node->left != nullptr) q.push(node->left); if (node->right != nullptr) q.push(node->right); } if (!evenflag) { reverse(cur.begin(), cur.end()); } evenflag = !evenflag; res.push_back(cur); } return res; } };
层序遍历的过程中加上一个偶层数的标志