-
Notifications
You must be signed in to change notification settings - Fork 267
/
BinaryTree.cpp
110 lines (89 loc) · 2.13 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
#include <iostream>
using namespace std;
// Create a class for the BinaryTree
class BinaryTree {
// Create a struct for the TreeNode
struct TreeNode {
// Variables for the TreeNode
int data;
TreeNode *left;
TreeNode *right;
// Constructor for the TreeNode
TreeNode(int value) : data(value), left(nullptr), right(nullptr) {}
};
// Private Variables and Functions
private:
TreeNode *root;
// Insert Function
TreeNode *insert(TreeNode *root, int value) {
if (root == nullptr)
return new TreeNode(value);
if (value < root->data)
root->left = insert(root->left, value);
else
root->right = insert(root->right, value);
return root;
}
// Print Inorder Function
void printInorder(TreeNode *head) {
if (head != nullptr) {
printInorder(head->left);
cout << head->data << " ";
printInorder(head->right);
}
}
// Print Preorder Function
void printPreorder(TreeNode *head) {
if (head != nullptr) {
cout << head->data << " ";
printPreorder(head->left);
printPreorder(head->right);
}
}
// Print Postorder Function
void printPostorder(TreeNode *head) {
if (head != nullptr) {
printPostorder(head->left);
printPostorder(head->right);
cout << head->data << " ";
}
}
// Public Functions
public:
// Constructor
BinaryTree() : root(nullptr) {}
// Insert Function
void insert(int value) { root = insert(root, value); }
// Print Inorder Function
void printInorder() {
printInorder(root);
cout << endl;
}
// Print Preorder Function
void printPreorder() {
printPreorder(root);
cout << endl;
}
// Print Postorder Function
void printPostorder() {
printPostorder(root);
cout << endl;
}
};
int main() {
// Create tree
BinaryTree binaryTree;
binaryTree.insert(10);
binaryTree.insert(6);
binaryTree.insert(15);
binaryTree.insert(3);
binaryTree.insert(8);
binaryTree.insert(20);
cout << "InOrder: ";
binaryTree.printInorder();
cout << "PreOrder: ";
binaryTree.printPreorder();
cout << "PostOrder: ";
binaryTree.printPostorder();
return 0;
}