103. Binary Tree Zigzag Level Order Traversal
Given the root of a binary tree, return the zigzag level order traversal of its nodes’ values. (i.e., from left to right, then right to left for the next level and alternate between).
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 33 34 35 36 37 38 39 40 class Solution { vector<int > toRight (list<TreeNode*>& l) { vector<int > res; list<TreeNode*> next; for (auto & node : l) { res.push_back (node->val); if (node->left != nullptr ) next.push_back (node->left); if (node->right != nullptr ) next.push_back (node->right); } l = next; return res; } vector<int > toLeft (list<TreeNode*>& l) { vector<int > res = toRight (l); reverse (res.begin (), res.end ()); return res; } public : vector<vector<int >> zigzagLevelOrder (TreeNode* root) { if (root == nullptr ) return {}; vector<vector<int >> res; list<TreeNode*> nodes{root}; while (nodes.size ()) { if (!nodes.empty ()) res.push_back (toRight (nodes)); if (!nodes.empty ()) res.push_back (toLeft (nodes)); } return res; } };