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).
Example
Given binary tree
{3,9,20,#,#,15,7}
,3 / \ 9 20 / \ 15 7
return its zigzag level order traversal as:
[ [3], [20,9], [15,7] ]
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
vector<vector<int> > output;
if (root == NULL ) return output;
// Create two stacks to store alternate levels
stack<TreeNode*> s1; // For levels to be printed from right to left
stack<TreeNode*> s2; // For levels to be printed from left to right
// Push first level to first stack 's1'
s1.push(root);
while(!s1.empty() || !s2.empty())
{
vector<int> v1, v2;
while (!s1.empty())
{
TreeNode *p = s1.top();
s1.pop();
v1.push_back(p->val);
if (p->left) s2.push(p->left);
if (p->right) s2.push(p->right);
}
while (!s2.empty())
{
TreeNode *p = s2.top();
s2.pop();
v2.push_back(p->val);
if (p->right) s1.push(p->right);
if (p->left) s1.push(p->left);
}
if (v1.size()) output.push_back(v1);
if (v2.size()) output.push_back(v2);
}
return output;
}
};
No comments:
Post a Comment