-
Notifications
You must be signed in to change notification settings - Fork 0
/
Minheap_datastructure.cpp
79 lines (64 loc) · 1.37 KB
/
Minheap_datastructure.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
/*
downHeap procedure for a min heap data structure,
represented as node-based tree.
*/
Node* lesser(Node *n){
if(n->right != nullptr && n->left != nullptr){
if (n->left->value >= n->right->value){
return n->right;
}
else{
return n->left;
}
}
else if(n->right == nullptr && n->left != nullptr){
return n->left;
}
else if(n->right != nullptr && n->left == nullptr){
return n->right;
}
else{
return nullptr;
}
}
void downHeap(Node *n) {
Node *n_lesser = lesser(n);
if(n_lesser != nullptr){
if(n->value > n_lesser->value){
// swap the nodes
int intermediate = n_lesser->value;
n_lesser->value = n->value;
n->value = intermediate;
// recursion call
downHeap(n_lesser);
}
else{
return;
}
}
return;
}
void printTree(Node *n) {
if (!n) return;
std::cout << n->value << "(";
printTree(n->left);
std::cout << ")(";
printTree(n->right);
std::cout << ")";
}
int main() {
Node *n = new Node(100);
n->left = new Node(1);
n->right = new Node(2);
n->right->left = new Node(3);
n->right->right = new Node(4);
n->right->right->right = new Node(5);
downHeap(n);
std::cout << "Compact printout:" << std::endl;
printTree(n);
std::cout << std::endl << "Vertical printout:" << std::endl;
printTreeVertical(n);
delete n;
n = nullptr;
return 0;
}