-
Notifications
You must be signed in to change notification settings - Fork 3
/
LeftistTree.h
82 lines (82 loc) · 1.82 KB
/
LeftistTree.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
#pragma once
#include <utility>
namespace ds
{
//保证内存泄漏,没有拷贝控制,谁爱用谁用
template <typename K>
class LeftistTree
{
public:
struct Node
{
private:
K key;
int dist = 0;
Node *p = nullptr;
Node *left = nullptr, *right = nullptr;
Node(const K &key) :key(key) {}
public:
const K &getKey()const { return key; }
friend LeftistTree;
};
private:
Node *root = nullptr;
LeftistTree(Node *root) :root(root) {}
static int dist(Node *x) { return x ? x->dist : -1; }
static Node *merge(Node *x,Node *y)
{
if (!x) return y;
if (!y) return x;
if (x->key > y->key) //小根
std::swap(x, y);
Node *tmp = merge(x->right, y);
x->right = tmp, tmp->p = x;
if (dist(x->right) > dist(x->left))
std::swap(x->left, x->right);
x->dist = dist(x->right) + 1;
return x;
}
public:
LeftistTree() :root(nullptr) {}
LeftistTree(const K &key) :root(new Node(key)) {}
void merge(LeftistTree &rhs)
{
if (this != &rhs)
{
root = merge(root, rhs.root);
rhs.root = nullptr;
}
}
//请自觉保证树非空
const K &top()const { return root->key; }
void pop()
{
root = merge(root->left, root->right);
}
Node *push(const K&key)
{
Node *x = new Node(key);
root = merge(root, x);
return x;
}
void erase(Node *x)
{
Node *tmp = merge(x->left, x->right);
if (!x->p) { root = tmp; return; }
if (tmp) tmp->p = x->p;//本身x的两个孩子就是nullptr,所以tmp可能是nullptr
if (x->p->right == x) x->p->right = tmp;
else x->p->left = tmp;
x = tmp;
while (x && x->p)
{
if (dist(x->p->right) > dist(x->p->left))
std::swap(x->p->left, x->p->right);
if (dist(x->p)==dist(x->p->right)+1)
break;
x->p->dist = dist(x->p->right) + 1;
x = x->p;
}
}
bool empty()const { return !root; }
};
}