1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
class Solution { public: vector<vector<int>> zigzagLevelOrder(TreeNode* root) { vector<vector<int>> res; queue<TreeNode *> q{{root}}; while (!q.empty()) { res.push_back({}); for (int i = q.size(); i > 0; --i) { auto x = q.front(); q.pop(); if (x) { res.back().push_back(x->val); q.push(x->left); q.push(x->right); } } if (!(res.size() & 1)) { reverse(begin(res.back()), end(res.back())); } } res.pop_back(); return res; } };
|