您的位置:首页 > 其它

Binary Tree Zigzag Level Order Traversal

2015-10-08 18:59 267 查看
/**
* 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查找,这种题目多熟悉熟悉就会做了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: