1天1道LeetCode
本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github
欢迎大家关注我的新浪微博,我的新浪微博
欢迎转载,转载请注明出处
(1)题目
来源: https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
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,15,7],
3
/
9 20
/
15 7
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]
(2)解题
题目大意:给定1个2叉树,按层序遍历输出,层数从1开始,奇数层从左往右输出,偶数层从右往左输出。
解题思路:上1题【1天1道LeetCode】#102. Binary Tree Level Order Traversal采取queue的数据结构来层序输出,每层都是按从左往右的顺序输出,所以,这1题可以采取deque的数据结构,根据奇数和偶数层来判断输出顺序。
详细解释见代码:
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> ret;
if(root==NULL) return ret;
deque<TreeNode*> deq;
deq.push_back(root);
int n = 1;
while(!deq.empty())
{
vector<int> tempnode;
deque<TreeNode*> temp;
while(!deq.empty()){
if(n%2==1)
{
TreeNode* tn = deq.front();
tempnode.push_back(tn->val);
deq.pop_front();
if(tn->left!=NULL) temp.push_back(tn->left);
if(tn->right!=NULL) temp.push_back(tn->right);
}
else
{
TreeNode* tn = deq.back();
tempnode.push_back(tn->val);
deq.pop_back();
if(tn->right!=NULL) temp.push_front(tn->right);
if(tn->left!=NULL) temp.push_front(tn->left);
}
}
deq = temp;
ret.push_back(tempnode);
n++;
}
return ret;
}
};