题目
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;
}
};