103. Binary Tree Zigzag Level Order Traversal
2015-08-09 19:25
405 查看
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
return its zigzag level order traversal as:
分析:首先肯定的是要对树进行层序遍历,但是相邻两层的元素遍历顺序是相反的,因此传统的非递归遍历方法用一个队列肯定是无法实现。我们用两个栈来实现,同一层元素都在同一个栈中,相邻的两层元素放在不同的栈中,比如第一层元素放在第一个栈,那么第二层就放在第二个栈,第三层就放在第三个栈......如果某一层元素是从左往右遍历的,那么这层元素的孩子节点入栈顺序就是先左孩子后右孩子,相反如果某一层元素是从右往左遍历的,入栈顺序就是先右孩子后左孩子。
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] ]
分析:首先肯定的是要对树进行层序遍历,但是相邻两层的元素遍历顺序是相反的,因此传统的非递归遍历方法用一个队列肯定是无法实现。我们用两个栈来实现,同一层元素都在同一个栈中,相邻的两层元素放在不同的栈中,比如第一层元素放在第一个栈,那么第二层就放在第二个栈,第三层就放在第三个栈......如果某一层元素是从左往右遍历的,那么这层元素的孩子节点入栈顺序就是先左孩子后右孩子,相反如果某一层元素是从右往左遍历的,入栈顺序就是先右孩子后左孩子。
/** * Definition for binary tree * 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) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. vector<vector<int> >res; if(root == NULL)return res; stack<TreeNode*> S,S2; S.push(root); bool isS = true; vector<int>tmpres; while(S.empty() == false || S2.empty() == false) { TreeNode *p; if(isS) { p = S.top(); S.pop(); tmpres.push_back(p->val); if(p->left)S2.push(p->left); if(p->right)S2.push(p->right); if(S.empty() == true) { res.push_back(tmpres); tmpres.clear(); isS = false; } } else { p = S2.top(); S2.pop(); tmpres.push_back(p->val); if(p->right)S.push(p->right); if(p->left)S.push(p->left); if(S2.empty() == true) { res.push_back(tmpres); tmpres.clear(); isS = true; } } } return res; } };
相关文章推荐
- I学霸官方免费教程三:Java基础之注释 关键字 标识符
- 2015年7月份来的知识回顾
- 单元测试junit
- 说一说Android的工程目录结构
- VSTS负载测试——如何:使用 SQL 创建结果存储区
- Scala 深入浅出实战经典 第52讲:Scala中路径依赖代码实战详解
- c语言中 指针和一维数组 简要总结
- 栈 链表的实现
- 第一周工作总结及计划表
- gerrit H2 数据库管理
- sdnu 1087.过河(NOIP 2005 提高组)DP状态压缩
- CS224d Problem set 2作业
- 《R语言实战》读书笔记--第三章 图形初阶(二)
- 区间覆盖
- (原)数据结构——线索二叉树
- B. Berland National Library
- Ubuntu 安装mysql和简单操作
- 如何实时查看linux下的日志
- uva 673 Parentheses Balance
- iOS开发--UIButton 设置圆角 边框颜色 点击回调方法