-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathheap.cpp
62 lines (56 loc) · 1.35 KB
/
heap.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
#include <iostream>
using namespace std;
class Node{
public:
Node* left;
Node* right;
Node* parent;
int value;
Node(int v){
value = v;
left = nullptr;
right = nullptr;
parent = nullptr;
}
};
class DecreasingHeap{
public:
DecreasingHeap(){}
bool is_empty(){
return root==nullptr;
}
void add(int value){
add(root,value);
}
private:
Node* root = nullptr;
int length = 0;
void add(Node* temp,int value){
if(is_empty()){
root = new Node(value);
length++;
}else if(value<=temp->value){
if(temp->left!=nullptr){
add(temp->left, value);
}else{
temp->left = new Node(value);
temp->left->parent=temp;
length++;
}
}else if(value > temp->value){
if(temp->right!=nullptr){
add(temp->right, value);
}else{
temp->right = new Node(value);
swap(temp,temp->right);
temp->right->parent=temp;
length++;
}
}
}
void swap(Node* &a, Node* &b){
Node* temp = a;
a = b;
b = temp;
}
};