-
Notifications
You must be signed in to change notification settings - Fork 0
/
6.cpp
112 lines (84 loc) · 1.74 KB
/
6.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
111
112
#include <iostream>
using namespace std;
struct Node {
public:
Node* left;
Node* right;
int value;
};
class Heap {
public:
short size;
Node* heap;
Heap();
bool addToHeap(int data);
void findLeavesSum(Node* child, int& sum);
int findHeapSum();
};
Heap::Heap() {
heap = NULL;
size = 0;
}
void Heap::findLeavesSum(Node* child, int& sum) {
if (child != NULL) {
sum += child->value;
findLeavesSum(child->left, sum);
findLeavesSum(child->right, sum);
}
}
int Heap::findHeapSum() {
int sum = 0;
this->findLeavesSum(heap, sum);
return sum;
}
bool Heap::addToHeap(int value) {
Node* tempNode, *temp = heap;
Node* parent = NULL;
int tempValue;
int index;
short mask = 0x80;
tempNode = new Node;
size++;
index = size;
while (!(index & mask)) {
index <<= 1;
}
index <<= 1;
while (temp) {
if (value > temp->value) {
tempValue = temp->value;
temp->value = value;
value = tempValue;
}
parent = temp;
if (!(index & mask)) {
temp = temp->left;
}
else {
temp = temp->right;
}
if (temp) {
index <<= 1;
}
}
tempNode->left = NULL;
tempNode->right = NULL;
tempNode->value = value;
if (!parent) {
heap = tempNode;
return true;
}
if (!(index & mask)) parent->left = tempNode;
else parent->right = tempNode;
return true;
}
int main() {
Heap heap;
heap.addToHeap(6);
heap.addToHeap(9);
heap.addToHeap(10);
heap.addToHeap(3);
heap.addToHeap(1);
cout <<"Heap sum: " << heap.findHeapSum() << endl;
return 0;
}