这题是102层序遍历的推广,我们只需要在合适的层翻转原始访问顺序就可以了, 普通的层序遍历可参考102题解,这里不再赘述。
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>>res;
if(root == NULL) return res;
queue<TreeNode *>q;
TreeNode *p;
bool left_to_right = true;
q.push(root);
while(!q.empty()){
vector<int>level;
for(int i = q.size(); i > 0; i--){
p = q.front();
q.pop();
level.push_back(p -> val);
if(p -> left) q.push(p -> left);
if(p -> right) q.push(p -> right);
}
if(!left_to_right) reverse(level.begin(), level.end()); // 翻转原始访问顺序
left_to_right = !left_to_right;
res.push_back(level);
}
return res;
}
};