leetcode #103 in cpp
来源:互联网 发布:淘宝优惠券小程序 编辑:程序博客网 时间:2024/06/07 19:14
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]]
Solution:
Traverse the tree level by level. Since we want the zig-zag, we change the order of pushing left child and right child. For details please view the code.
Code:
/** * 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>>res; deque<TreeNode*> nodes; stack<TreeNode*> stk; if(!root) return res; nodes.push_back(root); bool isl = true;//travel from left to right while(!nodes.empty()){ vector<int> member; int cap = nodes.size(); int i = 0; while(i < cap){ TreeNode *node = nodes.front(); //nodes has been in the order we want, simply push it into member. member.push_back(node->val); nodes.pop_front(); if(isl){//the order by which we push left child and right child depends on what direction is it in the next level if(node->left) stk.push(node->left); if(node->right) stk.push(node->right); } else{ if(node->right) stk.push(node->right); if(node->left) stk.push(node->left); } i++; } while(!stk.empty()){ nodes.push_back(stk.top()); stk.pop(); } res.push_back(member); isl = isl?false:true; } return res; } };
0 0
- leetcode #103 in cpp
- leetcode #12 in cpp
- Leetcode #13 in cpp
- Leetcode #14 in cpp
- leetcode %15 in cpp
- leetcode #16 in cpp
- leetcode #17 in cpp
- leetcode #18 in cpp
- leetcode #20 in cpp
- leetcode #21 in cpp
- leetcode #22 in cpp
- leetcode #23 in cpp
- leetcode #24 in cpp
- leetcode #25 in cpp
- leetcode #26 in cpp
- leetcode #27 in cpp
- leetcode #28 in cpp
- leetcode #29 in cpp
- mysql的alter命令
- linux技巧
- 读《携程异步消息系统实践》之总结
- csdn待改进点之13------>每次评论博文, 平均约5s才有显示成功, 请不要跟我说这是网络问题
- Android图片压缩学习
- leetcode #103 in cpp
- TextView实现跑马灯效果
- UI控件的公共属性
- 谈谈对Spring IOC的理解
- 桶排序
- 系统权限进入mysql数据库看不到自己建立的数据库的解决办法
- 匹配包含换行符(回车)的任意字符串的正则表达式
- Android Studio建立jni开发环境
- 冒泡排序