<LeetCode OJ> 103. Binary Tree Zigzag Level Order Traversal
2016-02-23 14:46
507 查看
103. Binary Tree Zigzag Level Order Traversal
My SubmissionsQuestion
Total Accepted: 54617 Total
Submissions: 194980 Difficulty: Medium
Given a binary tree, return the zigzag level order traversal of its nodes' values.
(ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree
{3,9,20,#,#,15,7},
3 / \ 9 20 / \ 15 7
return its zigzag level order traversal as:
[ [3], [20,9], [15,7] ]
confused what
"{1,#,2,3}"means? >
read more on how binary tree is serialized on OJ.
Subscribe to see which companies asked this question
Hide Tags
Tree Breadth-first
Search Stack
Show Similar Problems
分析:
这个问题和前面问题没有本质的区别吧?
<LeetCode OJ> 102. / 107. Binary Tree
Level Order Traversal(I / II),
博客地址,http://blog.csdn.net/ebowtang/article/details/50719417
唯一的区别就是奇数层和偶数层的压入顺序相反而已。
/** * 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==NULL) return result; queue<TreeNode*> que;//用来总是保存当层的节点 que.push(root); int level=1; //获取每一层的节点 while(!que.empty()) { int levelNum = que.size();//通过size来判断当层的结束 vector<int> curlevel; for(int i=0; i<levelNum; i++) { if(que.front()->left != NULL) //先获取该节点下一层的左右子,再获取该节点的元素,因为一旦压入必弹出,所以先处理左右子 que.push(que.front()->left); if(que.front()->right != NULL) que.push(que.front()->right); if(level&0x0001) //奇数层,或者if(level%2==1) curlevel.push_back(que.front()->val); else//偶数层 curlevel.insert(curlevel.begin(),que.front()->val); que.pop(); } level++; result.push_back(curlevel); } return result; } };
注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!
原文地址:http://blog.csdn.net/ebowtang/article/details/50723062
原作者博客:http://blog.csdn.net/ebowtang
相关文章推荐
- HDU 1166 敌兵布阵(区间求和&(线段树|树状数组))
- easyUI 中datagrid控件从后台获取数据生成列,想让其中部分属性数据不在表中显示
- JAVA的Random类(转)
- MySQL 高可用架构在业务层面细化分析研究
- 我的Android进阶之旅------>解决:Failed to create 'build\outputs\apk\watch-debug-unaligned.apks': 拒绝访问。
- Eclips图标含义整理
- Struts.xml配置中的包介绍
- Xcode中的 workspace, project, target, scheme
- How To Determine Web Application Thread Pool Size
- Android allowTaskReparenting clearTaskOnLaunch alwaysRetainTaskState
- SpringMVC源码解读 - HandlerMapping - RequestMappingHandlerMapping请求分发
- android中按电源键锁屏然后解锁导致Activity调用onDestory以及如何防止锁屏
- redis持久化存储
- Ubuntu 简单创建 FTP 相关配置
- 删数问题
- 使用Auto Layout中的VFL(Visual format language)--代码实现自动布局
- 动态生成一个textview,设置padding不起作用的解决办法。
- JFinal源码解析一:JFinal是做什么用的,有什么特点
- 1.C++远航之起航篇
- 用文件锁排他锁实现商品秒杀、抢购