-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSkewHeap.java
More file actions
87 lines (73 loc) · 2.09 KB
/
Copy pathSkewHeap.java
File metadata and controls
87 lines (73 loc) · 2.09 KB
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
public class SkewHeap {
Node root;
public SkewHeap(Node node){
this.root = node;
}
public SkewHeap merge(SkewHeap heap1, SkewHeap heap2){
if (heap1 == null){
return heap2;
}else if (heap2 == null){
return heap1;
}else {
heap1.root = merge(heap1.root, heap2.root);
return heap1;
}
}
public Node merge(Node node1, Node node2){
if (node1 == null && node2 == null){
return null;
}
if (node1 == null){
swapSubtrees(node2);
return node2;
}
if (node2 == null){
swapSubtrees(node1);
return node1;
}
if (node1.value > node2.value){
Node temp = node1;
node1 = node2;
node2 = temp;
}
swapSubtrees(node1);
node1.leftChild = merge(node1.leftChild, node2);
return node1;
}
public void add(Node node){
root = merge(root, node);
}
public Node remove(){
Node leftSubtree = root.leftChild;
Node rightSubtree = root.rightChild;
Node removedNode = root;
root = merge(leftSubtree, rightSubtree);
return removedNode;
}
public void swapSubtrees(Node node){
if (node.rightChild != null && node.leftChild != null){
Node temp = node.rightChild;
node.rightChild = node.leftChild;
node.leftChild = temp;
}
if (node.leftChild != null || node.rightChild != null){
if (node.leftChild == null) {
node.leftChild = node.rightChild;
node.rightChild = null;
}
if (node.rightChild == null) {
node.rightChild = node.leftChild;
node.leftChild = null;
}
}
}
}
class Node{
Node leftChild;
Node rightChild;
int value;
public Node(int value){
this.value = value;
leftChild = rightChild = null;
}
}