题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
https://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
层序遍历,加个flag转向就行了
class Solution { public: vector<vector<int>> Print(TreeNode* pRoot) { vector<vector<int>> res; if (!pRoot) return res; queue<TreeNode*> q; q.push(pRoot); bool rev = false; while (!q.empty()) { int n = q.size(); vector<int> tmp; for (int i = 0; i < n; i++) { if (q.front()->left) q.push(q.front()->left); if (q.front()->right) q.push(q.front()->right); tmp.push_back(q.front()->val); q.pop(); } if (rev) reverse(tmp.begin(), tmp.end()); rev = !rev; res.push_back(tmp); } return res; } };