-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinaryTree.cpp
169 lines (134 loc) · 2.68 KB
/
BinaryTree.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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
// building BT and implementing different tree traversals
// Node class
class Node
{
public:
int data;
Node *left;
Node *right;
Node(int val)
{
data = val;
left = right = NULL;
}
};
static int idx = -1;
Node *buildTree(vector<int> preorder)
{
idx++;
// base case
if (preorder[idx] == -1)
{
return NULL;
}
// create root node
Node *root = new Node(preorder[idx]);
// left sub tree recursion call
root->left = buildTree(preorder);
// left sub tree recursion call
root->right = buildTree(preorder);
return root;
}
// preorder traversal
void preOrder(Node *root)
{
// base case
if (root == NULL)
{
return;
}
// print root
cout << root->data << " ";
// recursive call for left sub tree
preOrder(root->left);
// recursive call for right sub tree
preOrder(root->right);
}
// inorder traversal
void inOrder(Node *root)
{
// base case
if (root == NULL)
{
return;
}
// recursive call for left sub tree
inOrder(root->left);
// print root
cout << root->data << " ";
// recursive call for right sub tree
inOrder(root->right);
}
// postorder traversal
void postOrder(Node *root)
{
// base case
if (root == NULL)
{
return;
}
// recursive call for left sub tree
postOrder(root->left);
// recursive call for right sub tree
postOrder(root->right);
// print root
cout << root->data << " ";
}
// level order traversal
void levelOrder(Node *root)
{
queue<Node *> q;
// push root
q.push(root);
// to mark level of tree
q.push(NULL);
while (q.size() > 0)
{
Node *curr = q.front();
q.pop();
if (curr == NULL)
{
// next line case
if (!q.empty())
{
cout << endl;
q.push(NULL);
continue;
}
// empty tree case
else
{
break;
}
}
cout << curr->data << " ";
// push left sub tree
if (curr->left != NULL)
{
q.push(curr->left);
}
// push right sub tree
if (curr->right != NULL)
{
q.push(curr->right);
}
}
cout << endl;
}
int main()
{
vector<int> preorder = {1, 2, -1, -1, 3, 4, -1, -1, 5, -1, -1};
Node *root = buildTree(preorder);
preOrder(root);
cout << endl;
inOrder(root);
cout << endl;
postOrder(root);
cout << endl;
levelOrder(root);
return 0;
}