版本比较
平衡树学习笔记
正文
增加 20 行删除 20 行
6 行未改动7891011111213141534 行未改动505152535454555657585960616162636464656666676869707172737374757676777878798081822 行未改动8586878889899091929333 行未改动12712812913013113113213313413517 行未改动1531541551561571571581591601611621631641651661671671681691701711721731741751761771771781791801811821831841851851861871881891901911921931931941951961971981992002002012022032042052052062072082092102102112122132142152152162172182192202202212222232248 行未改动6 行未改动
当然,平衡树不止有 AVL 树一种,像后面出现的 Treap, Splay树 , 红黑树等都是平衡树的实现。我们先说AVL树 ~~_(其实是因为作者之前只写了AVL树)_~~
## AVL 树AVL 树,是一种平衡的二叉搜索树。由于各种算法教材上对 AVL 的介绍十分冗长,造成了很多人对 AVL 树复杂、不实用的印象。但实际上,AVL 树的原理简单,实现也并不复杂。 _~~(但是作者预习的时候是觉得AVL树比较稳定,会先讲,然后才先学的,结果讲了Treap,而且写了旋转函数没加引用符号,改代码改了一节课,最后自己发现的......)~~_ AVL 树,是一种平衡的二叉搜索树。由于各种算法教材上对 AVL 的介绍十分冗长,造成了很多人对 AVL 树复杂、不实用的印象。但实际上,AVL 树的原理简单,实现也并不复杂。 _~~(但是作者预习的时候是觉得AVL树比较稳定,会先讲,然后才先学的,结果讲了Treap,而且写了旋转函数没加引用符号,改代码改了一节课,最后自己发现的......)~~_
### 性质1. 空二叉树是一个 AVL 树2. 如果 T 是一棵 AVL 树,那么其左右子树也是 AVL 树,并且 $|h(ls) - h(rs)| \leq 1$,h 是其左右子树的高度34 行未改动 if (!id) return; tree[id].size = tree[ls(id)].size + tree[rs(id)].size + tree[id].cnt; tree[id].high = max(tree[ls(id)].high, tree[rs(id)].high) + 1; }
inline void left(int &id) { int temp = rs(id); rs(id) = ls(temp); ls(temp) = id; id = temp;
pushup(ls(id)); pushup(id);
}
inline void right(int &id) { int temp = ls(id); ls(id) = rs(temp); rs(temp) = id; id = temp;
pushup(rs(id)); pushup(id);
}
inline int newNode(int v) { tree[++tot].val = v; // tree[tot].high = 0;2 行未改动 tree[tot].size = 1; //60 tree[tot].cnt = 1; return tot; }
void insert(int &id, int v) { if (!id) {33 行未改动 } tree[id].cnt ++; pushup(id); }
void del(int &id, int v) { if (!id) return; if (tree[id].val == v)17 行未改动 del(ls(id), v); else del(rs(id), v); pushup(id); }
int Rank(int id, int v) { if (!id) return 1; if (tree[id].val == v) return tree[ls(id)].size + 1; if (tree[id].val < v) return tree[ls(id)].size + Rank(rs(id), v) + tree[id].cnt; return Rank(ls(id), v); }
int xth(int id, int rank) { if (!id) return INF; if (rank <= tree[ls(id)].size) return xth(ls(id), rank); if (rank <= tree[ls(id)].size + tree[id].cnt) return tree[id].val; return xth(rs(id), rank - tree[ls(id)].size - tree[id].cnt); }
int pre(int id, int v) { if (!id) return -INF; if (tree[id].val < v) return max(tree[id].val, pre(rs(id), v)); return pre(ls(id), v); }
int sub(int id, int v) { if (!id) return INF; if (tree[id].val > v) return min(tree[id].val, sub(ls(id), v)); return sub(rs(id), v); }
public: //共有的,即外部可用的,一般只有函数,比如queue队列,只有front()等 //重载,因为root在类内,有inline对效率得影响几乎没有 inline void insert(int v) { insert(root, v); }
inline void del(int v) { del(root, v); }
inline int Rank(int v) { return Rank(root, v); }
inline int xth(int rank) { return xth(root, rank); }
inline int pre(int v) { return pre(root, v); }
inline int sub(int v) { return sub(root, v); }8 行未改动