题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
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* pRoot) { // write code here vector<vector<int>> ans; if (pRoot == NULL) { return ans; } queue<TreeNode* > que; que.push(pRoot); int cnt = 0; while(!que.empty()) { int size = que.size(); vector<int> res; for (int i = 0;i < size;i++) { TreeNode* node = que.front(); que.pop(); res.push_back(node->val); if (node->left) que.push(node->left); if (node->right) que.push(node->right); } if (cnt % 2 == 1) { reverse(res.begin(),res.end()); } ans.push_back(res); cnt += 1; } return ans; } };