-
Notifications
You must be signed in to change notification settings - Fork 69
/
Zigzag order traversal.cpp
89 lines (75 loc) · 1.69 KB
/
Zigzag order traversal.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// C++ implementation of a O(n) time method for
// Zigzag order traversal
#include <iostream>
#include <stack>
using namespace std;
// Binary Tree node
struct Node {
int data;
struct Node *left, *right;
};
// function to print the zigzag traversal
void zizagtraversal(struct Node* root)
{
// if null then return
if (!root)
return;
// declare two stacks
stack<struct Node*> currentlevel;
stack<struct Node*> nextlevel;
// push the root
currentlevel.push(root);
// check if stack is empty
bool lefttoright = true;
while (!currentlevel.empty()) {
// pop out of stack
struct Node* temp = currentlevel.top();
currentlevel.pop();
// if not null
if (temp) {
// print the data in it
cout << temp->data << " ";
// store data according to current
// order.
if (lefttoright) {
if (temp->left)
nextlevel.push(temp->left);
if (temp->right)
nextlevel.push(temp->right);
}
else {
if (temp->right)
nextlevel.push(temp->right);
if (temp->left)
nextlevel.push(temp->left);
}
}
if (currentlevel.empty()) {
lefttoright = !lefttoright;
swap(currentlevel, nextlevel);
}
}
}
// A utility function to create a new node
struct Node* newNode(int data)
{
struct Node* node = new struct Node;
node->data = data;
node->left = node->right = NULL;
return (node);
}
// driver program to test the above function
int main()
{
// create tree
struct Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(7);
root->left->right = newNode(6);
root->right->left = newNode(5);
root->right->right = newNode(4);
cout << "ZigZag Order traversal of binary tree is \n";
zizagtraversal(root);
return 0;
}