103-Binary Tree Zigzag Level Order Traversal
来源:互联网 发布:什么叫国内数据流量 编辑:程序博客网 时间:2024/05/18 02:19
题目
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,null,null,15,7]
3 / \ 9 20 / \ 15 7
return its zigzag level order traversal as:
[ [3], [20,9], [15,7]]
分析
访问顺序分为奇数行和偶数行。
实现
class Solution {public:vector<vector<int>> zigzagLevelOrder(TreeNode * root) { vector<vector<int>> res; if (!root) return res; vector<int> tmpRes; TreeNode *curr = NULL; stack<TreeNode* > stack1, stack2; stack1.push(root); // stack1 保存奇数层的结点 // stack2 保存偶数层的结点 while (!stack1.empty() || !stack2.empty()) { //访问奇数层的结点,并将下一层的结点存入stack2 while (!stack1.empty()) { curr = stack1.top(); tmpRes.push_back(curr->val); stack1.pop(); if (curr->left) stack2.push(curr->left); if (curr->right) stack2.push(curr->right); } if(!tmpRes.empty()) res.push_back(tmpRes); tmpRes.clear(); //访问偶数层的结点,并将下一层的结点存入stack1 while (!stack2.empty()) { curr = stack2.top(); tmpRes.push_back(curr->val); stack2.pop(); if (curr->right) stack1.push(curr->right); if (curr->left) stack1.push(curr->left); } if(!tmpRes.empty()) res.push_back(tmpRes); tmpRes.clear(); } return res; }};
阅读全文
0 0
- 103 Binary Tree Zigzag Level Order Traversal
- 103-Binary Tree Zigzag Level Order Traversal
- LeetCode: Binary Tree Zigzag Level Order Traversal
- [LeetCode]Binary Tree Zigzag Level Order Traversal
- LeetCode Binary Tree Zigzag Level Order Traversal
- [Leetcode] Binary Tree Zigzag Level Order Traversal
- Leetcode: Binary Tree Zigzag Level Order Traversal
- LeetCode Binary Tree Zigzag Level Order Traversal
- [LeetCode] Binary Tree Zigzag Level Order Traversal
- [Leetcode] Binary Tree Zigzag Level Order Traversal
- Binary Tree Zigzag Level Order Traversal
- 【leetcode】Binary Tree Zigzag Level Order Traversal
- [LeetCode]Binary Tree Zigzag Level Order Traversal
- Binary Tree Zigzag Level Order Traversal
- Binary Tree Zigzag Level Order Traversal
- [Leetcode]Binary Tree Zigzag Level Order Traversal
- [leetcode]Binary Tree Zigzag Level Order Traversal
- Leetcode: Binary Tree Zigzag Level Order Traversal
- Android数据库GreenDAO3.2.2的使用(一,集成数据库)
- 102-Binary Tree Level Order Traversal
- 大泥球的成长之路
- _tprintf打印中文问题
- OBS窗口捕获黑屏的解决办法
- 103-Binary Tree Zigzag Level Order Traversal
- CSS清除浮动使父级元素展开
- 108-Convert Sorted Array to Binary Search Tree
- css3中scale的效果
- 读书笔记-人月神话6
- JS中2个感叹号的作用
- PHP常见9大缓存
- Satisfactory Pairs
- 对象引用计数器