-
Notifications
You must be signed in to change notification settings - Fork 1
/
MoviesTree.h
83 lines (68 loc) · 2.03 KB
/
MoviesTree.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
71
72
73
74
75
76
77
78
79
80
81
82
83
#ifndef MOVIESTREE_H
#define MOVIESTREE_H
#include <iostream>
#include <vector>
using namespace std;
class TreeNode {
public:
MovieNode* movie;
double resemblance; // Changed to double to match with weight in RecommendationGraph
TreeNode* left;
TreeNode* right;
TreeNode(MovieNode* movie, double resemblance) {
this->movie = movie;
this->resemblance = resemblance;
this->left = nullptr;
this->right = nullptr;
}
};
class RecommendationHeap {
private:
vector<TreeNode*> heap;
void heapifyUp(int index) {
int parent = (index - 1) / 2;
while (index > 0 && heap[index]->resemblance > heap[parent]->resemblance) {
swap(heap[index], heap[parent]);
index = parent;
parent = (index - 1) / 2;
}
}
void heapifyDown(int index) {
int leftChild = 2 * index + 1;
int rightChild = 2 * index + 2;
int largest = index;
if (leftChild < heap.size() && heap[leftChild]->resemblance > heap[largest]->resemblance) {
largest = leftChild;
}
if (rightChild < heap.size() && heap[rightChild]->resemblance > heap[largest]->resemblance) {
largest = rightChild;
}
if (largest != index) {
swap(heap[index], heap[largest]);
heapifyDown(largest);
}
}
public:
void insert(TreeNode* node) {
heap.push_back(node);
heapifyUp(heap.size() - 1);
}
TreeNode* extractMax() {
if (heap.empty()) {
return nullptr;
}
TreeNode* maxNode = heap[0];
heap[0] = heap.back();
heap.pop_back();
heapifyDown(0);
return maxNode;
}
void printHeapByPriority() {
while (!heap.empty()) {
TreeNode* temp = extractMax();
temp->movie->display();
delete temp; // Free the memory of the printed node
}
}
};
#endif // MOVIESTREE_H