/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> result;
if(root==nullptr) return result;
queue<TreeNode*> q;
q.push(root);
int cnt=0;
while(!q.empty()){
int size=q.size();
cnt++;
vector<int> sub_result;
for(int i=0;i<size;i++){
TreeNode* tmp = q.front();
q.pop();
sub_result.push_back(tmp->val);
if(tmp->left)q.push(tmp->left);
if(tmp->right)q.push(tmp->right);
}
if(cnt%2==0)reverse(sub_result.begin(),sub_result.end());
result.push_back(sub_result);
}
return result;
}
};
思路:BFS查找,这种题目多熟悉熟悉就会做了。