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查找,这种题目多熟悉熟悉就会做了。
相关文章推荐
- 235.Lowest Common Ancestor of a Binary Search Tree
- Linux系统磁盘查看清理方法
- 微型计算机的发展是以何种技术为特征标志的?微处理器
- el笔记!
- JQuery中两个ul标签的li互相移动实现方法
- HLG 1293 取数 二分
- C++primer学习:再探迭代器
- 226.Invert Binary Tree
- 新闻的频道订阅界面和功能
- OpenCv获取摄像头并显示摄像内容
- 笨得不够
- Word Pattern
- 10-5总结
- 第四周
- 智能车学习(二)—— GPIO学习
- 启动虚拟机时报错----不能为虚拟电脑 1008 打开一个新任务.
- bzoj 1046: [HAOI2007]上升序列
- 关于代码规范问题(启动活动的最佳写法)
- ecshop 获取某个商品的 所有订单信息 或者销量
- iOS效果 :(1) CALayer 图层阴影,边框,圆角,圆型图片的阴影