题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
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) {} * }; */ #include <algorithm> #include <queue> #include <vector> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param pRoot TreeNode类 * @return int整型vector<vector<>> */ vector<vector<int> > Print(TreeNode* pRoot) { // write code here vector<vector<int>> ans; if (pRoot == NULL) { return ans; } queue<TreeNode*> q; q.push(pRoot); int i = 1; bool reverse_flag = false; while (!q.empty()) { //记录下这一行的值 vector<int> row; int n = q.size(); //把这一行的数值放入row中 for (int j = 0; j < n; j++) { TreeNode* cur = q.front(); q.pop(); row.push_back(cur->val); if (cur->left) { q.push(cur->left); } if (cur->right) { q.push(cur->right); } } //当前行按照对应的规则放完,更新参数 if (reverse_flag) { reverse(row.begin(), row.end()); } ans.push_back(row); reverse_flag = !reverse_flag; } return ans; } };
之字形遍历二叉树
思路:
按照之前一样借助队列实现层序遍历
再每一层需要反转的时候,将row vector通过函数reverse(rwo.begin(), row.end)实现反转,然后push back到最大vector中
最终循环完毕,返回两层vector答案