Aryan PrajapatKnowledge Contributor
Write a function for zigzag traversal in a binary tree
Write a function for zigzag traversal in a binary tree
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Questions | Answers | Discussions | Knowledge sharing | Communities & more.
// Tree Node
struct Node {
int data;
Node* left;
Node* right;
};
//Function to store the zigzag order traversal of a tree in a list.
vector zigZagTraversal(Node* root)
{
//creating two stacks for level traversals in both order
stack st1;
stack st2;
//vector to store the zigzag traversal
vector result;
//Initialize the first stack with the root element
st1.push(root);
//Iterate until either of the stack is not empty
while(!st1.empty() || !st2.empty()){
//iterate until the first stack is not empty
while(!st1.empty()){
Node* temp=st1.top();
st1.pop();
result.push_back(temp->data);
if(temp->left)
st2.push(temp->left);
if(temp->right)
st2.push(temp->right);
}
//Iterate until the second stack is not empty
while(!st2.empty()){
Node* temp=st2.top();
st2.pop();
result.push_back(temp->data);
if(temp->right)
st1.push(temp->right);
if(temp->left)
st1.push(temp->left);
}
}
return result;
}