1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class Solution { public: vector<vector<int>> zigzagLevelOrder(TreeNode* root) { vector<vector<int>> ans; preorder(root, 0, ans); return ans; } private: void preorder(TreeNode* root, int level, vector<vector<int>>& ans) { if (root == nullptr) return; if (level >= ans.size()) ans.push_back(vector<int>()); auto& row = ans[level]; if (level % 2 == 0) row.push_back(root->val); else row.insert(row.begin(), root->val); preorder(root->left, level + 1, ans); preorder(root->right, level + 1, ans); } };
|