/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: vector<vector<int>> zigzagLevelOrder(TreeNode* root) { vector<vector<int>> res; if(root==NULL) return res; queue<TreeNode*> q; q.push(root); vector<int> temp; while(!q.empty()){ if(temp.size()>0) res.push_back(temp); int len = q.size(); temp.clear(); while(len--){ TreeNode* tmp = q.front(); q.pop(); temp.push_back(tmp->val); if(tmp->left) q.push(tmp->left); if(tmp->right) q.push(tmp->right); } } res.push_back(temp); for(int i = 0; i < res.size(); i++){ if(i%2==1) // 奇数行翻转 reverse(res[i].begin(), res[i].end()); } return res; } };