-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path04_BinaryTree.cpp
More file actions
89 lines (89 loc) · 2.09 KB
/
04_BinaryTree.cpp
File metadata and controls
89 lines (89 loc) · 2.09 KB
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
#include <bits/stdc++.h>
using namespace std;
#define endl "\n"
#define ll long long
class node {
public:
int data;
node *left, *right;
node(int data) {
this->data = data;
this->left = NULL;
this->right = NULL;
}
};
node *binaryTree(node *root) {
int data;
cout << "Enter Data: " << endl;
cin >> data;
root = new node(data);
if (data == -1) {
return NULL;
}
cout << "Left Node of parent " << data << " ";
root->left = binaryTree(root->left);
cout << "Right Node of parent " << data << " ";
root->right = binaryTree(root->right);
return root;
}
void levelOrderTraversal(node *root) {
queue<node *> q;
q.push(root);
q.push(NULL);
while (!q.empty()) {
node *temp = q.front();
q.pop();
if (temp == NULL) {
cout << endl;
if (!q.empty()) {
q.push(NULL);
}
} else {
cout << temp->data << " ";
if (temp->left) {
q.push(temp->left);
}
if (temp->right) {
q.push(temp->right);
}
}
}
}
void inorderTraversal(node *root) {
if (root == NULL) {
return;
}
inorderTraversal(root->left);
cout << root->data << " ";
inorderTraversal(root->right);
}
void preorderTraversal(node *root) {
if (root == NULL) {
return;
}
cout << root->data << " ";
preorderTraversal(root->left);
preorderTraversal(root->right);
}
void postorderTraversal(node *root) {
if (root == NULL) {
return;
}
postorderTraversal(root->left);
postorderTraversal(root->right);
cout << root->data << " ";
}
int main() {
node *root = NULL;
root = binaryTree(root);
cout << "Leverl Order Traversal:" << endl;
levelOrderTraversal(root);
cout << "In Order Traversal:" << endl;
inorderTraversal(root);
cout << endl << "Pre Order Traversal:" << endl;
preorderTraversal(root);
cout << endl << "Post Order Traversal:" << endl;
postorderTraversal(root);
cout << endl;
return 0;
}