-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtree.h
70 lines (58 loc) · 1.42 KB
/
tree.h
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
#ifndef TREE_H
#define TREE_H
#include "player.h"
//#include "node.h"
#include <iostream>
class Node {
public:
Player* value;
Node* left;
Node* right;
Node(Player* player) : value(player), left(nullptr), right(nullptr) {}
};
class Tree {
private:
Node* root;
Node* insert(Node* node, Player* player) {
if (!node) {
return new Node(player);
}
if (player->getPlayerAge() < node->value->getPlayerAge()) {
node->left = insert(node->left, player);
} else {
node->right = insert(node->right, player);
}
return node;
}
void inOrderTraversal(Node* node) const {
if (node) {
inOrderTraversal(node->left);
node->value->displayInfo();
inOrderTraversal(node->right);
}
}
void freeTree(Node* node) {
if (node) {
freeTree(node->left);
freeTree(node->right);
if (node->value) {
delete node->value;
node->value = nullptr;
}
delete node;
}
}
public:
Tree() : root(nullptr) {}
~Tree() {
freeTree(root);
}
void addPlayer(Player* player) {
root = insert(root, player);
}
void display() const {
std::cout << "\n--- Players by Age (Binary Tree In-Order Traversal) ---\n";
inOrderTraversal(root);
}
};
#endif // TREE_H