-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary_tree.cpp
82 lines (69 loc) · 1.61 KB
/
binary_tree.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
#include <iostream>
using namespace std;
class TreeNode {
public:
int data;
TreeNode* left;
TreeNode* right;
TreeNode(int value) {
data = value;
left = nullptr;
right = nullptr;
}
};
class BinaryTree {
private:
TreeNode* root;
public:
BinaryTree() {
root = nullptr;
}
void insert(int value) {
TreeNode* newNode = new TreeNode(value);
if (root == nullptr) {
root = newNode;
return;
}
TreeNode* current = root;
while (true) {
if (value < current->data) {
if (current->left == nullptr) {
current->left = newNode;
return;
}
current = current->left;
} else {
if (current->right == nullptr) {
current->right = newNode;
return;
}
current = current->right;
}
}
}
void printInOrder(TreeNode* node) {
if (node == nullptr) {
return;
}
printInOrder(node->left);
cout << node->data << " ";
printInOrder(node->right);
}
void printInOrderTraversal() {
cout << "In-order traversal: ";
printInOrder(root);
cout << endl;
}
};
int main() {
BinaryTree binaryTree;
binaryTree.insert(5);
binaryTree.insert(3);
binaryTree.insert(7);
binaryTree.insert(2);
binaryTree.insert(4);
binaryTree.insert(6);
binaryTree.insert(8);
binaryTree.printInOrderTraversal();
return 0;
}