The Leftist Tree is a data structure that maintains a multiset of numbers by maintaining a binary tree.
Specifically, in the binary tree, each node stores an element of . The binary tree satisfies that the element in each node is less than or equal to the element in its parent.
In addition, let denote the minimum number of steps required to reach an empty node, starting from node and walking down the binary tree. is also maintained for each node .
This requires space.
Lemma
Let denote the root of the binary tree, then
Proof
Lemma
Let denote the minimum size of a binary tree where the of the root is , then
Proof
For each in , if ,
By induction, it follows that
Applying the lemma yields
Merge
Merge merges two Leftist Trees of and , respectively, into a single Leftist Tree of in time and space.
Algorithm
Wlog, assume .
Let denote the root of the first Leftist Tree, and denote the left child and the right child of , respectively.
- If , merge the left sub-Leftist-Tree of with the second Leftist Tree recursively.
- Otherwise, merge the right sub-Leftist-Tree of with the second Leftist Tree recursively.
This algorithm solves the problem in time and space.
Node *merge(Node *x, Node *y) {
return [&](this auto &&self, Node *x, Node *y) -> Node * {
if (!x) {
return y;
}
if (!y) {
return x;
}
if (x->val < y->val) {
std::swap(x, y);
}
auto &z = (x->lch ? x->lch->d : 0) < (x->rch ? x->rch->d : 0) ? x->lch : x->rch;
z = self(z, y);
x->d = std::min(x->lch ? x->lch->d : 0, x->rch ? x->rch->d : 0) + 1;
return x;
} (x, y);
}