题目
给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
例如:给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回锯齿形层次遍历如下:
[
[3],
[20,9],
[15,7]
]
思路
双栈,一个栈先插左子树再插右子树,另一个先插右子树再插左子树
实现
/**
* 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) {
int flag = 1;
vector<vector<int>> res;
vector<int> temp;
stack<TreeNode*> s1;
stack<TreeNode*> s2;
if (root == NULL) return res;
s1.push(root);
int cur = 1;
int next = 0;
while (!s1.empty() || !s2.empty()) {
if (!s1.empty() ) {
while (!s1.empty()) {
TreeNode* a = s1.top();
if (a->left != NULL) {
s2.push(a->left);
}
if (a->right != NULL) {
s2.push(a->right);
}
temp.push_back(a->val);
s1.pop();
}
res.push_back(temp);
temp.clear();
}
if (!s2.empty()) {
while (!s2.empty()) {
TreeNode* a = s2.top();
if (a->right != NULL) {
s1.push(a->right);
}
if (a->left != NULL) {
s1.push(a->left);
}
temp.push_back(a->val);
s2.pop();
}
res.push_back(temp);
temp.clear();
}
}
return res;
}
};