forked from TARANG0503/DSA-Practice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Binary_tree_traversal_algorithms.cpp
121 lines (115 loc) · 2.15 KB
/
Binary_tree_traversal_algorithms.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
class Node
{
public:
int data;
Node *left;
Node *right;
Node(int val)
{
data = val;
left = NULL;
right = NULL;
}
};
class BinaryTree
{
int idx = -1;
public:
Node *BuildTree(int arr[])
{
idx++;
if (arr[idx] == -1)
{
return NULL;
}
Node *newNode = new Node(arr[idx]);
newNode->left = BuildTree(arr);
newNode->right = BuildTree(arr);
return newNode;
}
};
void preOrderTraversal(Node *root)
{
if (root == NULL)
{
cout << "NULL ";
}
else
{
cout << root->data << " ";
preOrderTraversal(root->left);
preOrderTraversal(root->right);
}
}
void inOrderTraversal(Node *root)
{
if (root == NULL)
{
cout << "NULL ";
}
else
{
inOrderTraversal(root->left);
cout << root->data << " ";
inOrderTraversal(root->right);
}
}
void PostOrderTraversal(Node *root)
{
if (root == NULL)
{
cout << "NULL ";
}
else
{
PostOrderTraversal(root->left);
PostOrderTraversal(root->right);
cout << root->data << " ";
}
}
void LevelOrderTraversal(Node *root)
{
queue<Node *> q;
q.push(root);
q.push(NULL);
while (!q.empty())
{
Node *newNode = q.front();
q.pop();
if (newNode == NULL)
{
cout << endl;
if (!q.empty())
{
q.push(NULL);
}
}
else
{
cout << newNode->data << " ";
if (newNode->left != NULL)
{
q.push(newNode->left);
}
if (newNode->right != NULL)
{
q.push(newNode->right);
}
}
}
}
int main()
{
int nodes[] = {1, 2, 4, -1, -1, 5, -1, -1, 3, -1, 6, -1, -1};
BinaryTree *tree = new BinaryTree();
Node *root = tree->BuildTree(nodes);
preOrderTraversal(root);
inOrderTraversal(root);
PostOrderTraversal(root);
LevelOrderTraversal(root);
return 0;
}