题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
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> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param pRoot TreeNode类 * @return int整型vector<vector<>> */ vector<vector<int> > Print(TreeNode* pRoot) { // write code here vector<vector<int>> w; if (pRoot == nullptr) return w; queue<TreeNode*> tree; stack<TreeNode*>st; int flag = 0; tree.push(pRoot); while (!tree.empty()) { vector<int> v; int size = tree.size(); while (size--) { pRoot = tree.front(); tree.pop(); v.push_back(pRoot->val); if (pRoot->left) tree.push(pRoot->left); if (pRoot->right) tree.push(pRoot->right); } if (flag % 2 == 1) { reverse(v.begin(), v.end()); } flag++; w.push_back(v); } return w; } };
层次遍历的基础上对奇数层,反转。