Skip to content

Commit 990e409

Browse files
author
Keith Kamer
committed
Added Binary Tree to C++
1 parent c67a20b commit 990e409

File tree

1 file changed

+126
-0
lines changed

1 file changed

+126
-0
lines changed

src/cpp/BinaryTree.cpp

+126
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
#include <iostream>
2+
3+
using namespace std;
4+
5+
// Create a class for the BinaryTree
6+
class BinaryTree
7+
{
8+
// Create a struct for the TreeNode
9+
struct TreeNode
10+
{
11+
// Variables for the TreeNode
12+
int data;
13+
TreeNode* left;
14+
TreeNode* right;
15+
16+
// Constructor for the TreeNode
17+
TreeNode(int value) : data(value), left(nullptr), right(nullptr) {}
18+
};
19+
20+
// Private Variables and Functions
21+
private:
22+
TreeNode* root;
23+
24+
//Insert Function
25+
TreeNode* insert(TreeNode* root, int value)
26+
{
27+
if (root == nullptr)
28+
return new TreeNode(value);
29+
30+
if (value < root->data)
31+
root->left = insert(root->left, value);
32+
else
33+
root->right = insert(root->right, value);
34+
35+
return root;
36+
}
37+
38+
// Print Inorder Function
39+
void printInorder(TreeNode* head)
40+
{
41+
if (head != nullptr)
42+
{
43+
printInorder(head->left);
44+
cout << head->data << " ";
45+
printInorder(head->right);
46+
}
47+
}
48+
49+
// Print Preorder Function
50+
void printPreorder(TreeNode* head)
51+
{
52+
if (head != nullptr)
53+
{
54+
cout << head->data << " ";
55+
printPreorder(head->left);
56+
printPreorder(head->right);
57+
}
58+
}
59+
60+
// Print Postorder Function
61+
void printPostorder(TreeNode* head)
62+
{
63+
if (head != nullptr)
64+
{
65+
printPostorder(head->left);
66+
printPostorder(head->right);
67+
cout << head->data << " ";
68+
}
69+
}
70+
71+
// Public Functions
72+
public:
73+
// Constructor
74+
BinaryTree() : root(nullptr) {}
75+
76+
// Insert Function
77+
void insert(int value)
78+
{
79+
root = insert(root, value);
80+
}
81+
82+
// Print Inorder Function
83+
void printInorder()
84+
{
85+
printInorder(root);
86+
cout << endl;
87+
}
88+
89+
// Print Preorder Function
90+
void printPreorder()
91+
{
92+
printPreorder(root);
93+
cout << endl;
94+
}
95+
96+
// Print Postorder Function
97+
void printPostorder()
98+
{
99+
printPostorder(root);
100+
cout << endl;
101+
}
102+
};
103+
104+
int main()
105+
{
106+
// Create tree
107+
BinaryTree binaryTree;
108+
109+
binaryTree.insert(10);
110+
binaryTree.insert(6);
111+
binaryTree.insert(15);
112+
binaryTree.insert(3);
113+
binaryTree.insert(8);
114+
binaryTree.insert(20);
115+
116+
cout << "InOrder: ";
117+
binaryTree.printInorder();
118+
119+
cout << "PreOrder: ";
120+
binaryTree.printPreorder();
121+
122+
cout << "PostOrder: ";
123+
binaryTree.printPostorder();
124+
125+
return 0;
126+
}

0 commit comments

Comments
 (0)