Traverse by Zig-Zag order
/***
zig-zag traversal of a binary tree.
***/
#include<iostream>
#include<stack>
#include<vector>
using namespace std;
struct node{
int val;
node *left, *right;
};
void zigzag(stack<node*> pre, vector<node*> *v, int flag) {
if(pre.empty()) return;
stack<node *> cur;
while(!pre.empty()) {
node *n = pre.top();
pre.pop();
v->push_back(n);
if(flag%2 == 0) {
if(n->left != nullptr) cur.push(n->left);
if(n->right != nullptr) cur.push(n->right);
} else {
if(n->right != nullptr) cur.push(n->right);
if(n->left != nullptr) cur.push(n->left);
}
}
zigzag(cur, v, flag+1);
}
void main() {
node n[7];
for(int i = 0; i<7; i++) {
n[i].val = i+1;
n[i].left = nullptr;
n[i].right = nullptr;
}
n[0].left = &n[1];
n[0].right = &n[2];
n[1].left = &n[3];
n[1].right = &n[4];
n[2].left = &n[5];
n[2].right = &n[6];
stack<node*> pre;
pre.push(n);
vector<node*> list;
zigzag(pre, &list, 0);
for(int i = 0; i < list.size(); i++)
cout<<list[i]->val<<"->";
cout<<endl;
}
Comments
Post a Comment