103. 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,null,15,7]
,
3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]
题目链接:https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal/
思路
想了一会儿没想出来,看了大佬提供的思路总结复现的。
其他还有这两种方案的递归版,但是我认为没有必要再写,因为递归和非递归是可互相转换的,而递归方法仍需要用栈辅助的话就没啥必要了。
法一:双栈
两个栈来记录节点,一个变量来判断左右子节点入栈的顺序。
/**
* 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;
if(root==NULL) return res;
stack<TreeNode*> st1;
st1.push(root);
bool isodd = true;
vector<int> restmp;
while(!st1.empty()){
stack<TreeNode*> st2;
while(!st1.empty()){
auto tmp = st1.top();
st1.pop();
restmp.push_back(tmp->val);
if(isodd){
if(tmp->left) st2.push(tmp->left);
if(tmp->right) st2.push(tmp->right);
}else{
if(tmp->right) st2.push(tmp->right);
if(tmp->left) st2.push(tmp->left);
}
}
res.push_back(restmp);
restmp.clear();
isodd = !isodd;
st1 = st2;
}
return res;
}
};
法二:deque
利用双头队列从两边入队出队,一个变量来判断出入的方向。
顺序取时:对头出,队尾入,先左后右;
逆序取时:队尾入,对头出,先右后左。
/**
* 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;
if(root==NULL) return res;
deque<TreeNode*> record;
record.push_back(root);
bool isodd = true;
while(!record.empty()){
int len = record.size();
vector<int> restmp;
for(int i=0; i<len; ++i){
TreeNode* tmp;
if(isodd){
tmp = record.front();
record.pop_front();
if(tmp->left) record.push_back(tmp->left);
if(tmp->right) record.push_back(tmp->right);
}else{
tmp = record.back();
record.pop_back();
if(tmp->right) record.push_front(tmp->right);
if(tmp->left) record.push_front(tmp->left);
}
restmp.push_back(tmp->val);
}
res.push_back(restmp);
isodd = !isodd;
}
return res;
}
};