@[TOC](Data Structure: Trees (树状数据结构))
数据结构存在的目的
数据结构便于数据管理data management和检索retrieval
复杂度概要
Binary Search Tree 二叉搜索树
BST property:
- 每个node最多有俩子节点
- 左子节点<父节点
- 右子节点>父节点
BST insertion:
- 保证BST property在insertion之后仍然保持
- Recursion大概步骤:
- if x>node: insert(right subtree)
- else: insert(left subtree)
- 直到subtree = null, 把x放下就行了
BST deletion:
考虑以下三种情况:
- If x has no children: then remove x
- If x has one child: then make p[x.child] point to p[x]
- If x has two children (subtrees): then replace x with its successor, delete successor in subtree
Balance Tree
- 属于BST
- 对于n个节点保证高度为 O(lg n)
- Height = maximum # edges from root to node
- E.g. AVL Trees, Red-Black Trees
Red-Black Tree 红黑树
- 红黑树接近于平衡树但不是完全平衡
- 树结构要求在每个节点中有一个额外的一位颜色bit:红色或黑色
- 色彩是用来保持平衡的
- 每一个节点包含: key, color, left, right, parent, (data).
Red-black properties:
- 每个节点是red或者black.
- Root and leaves都是black. (每一个node都只有2个children)
- 如果node是red的, 那么children必须是black. (*不能有两个连续的red)
- Every path from node to后代leave都包含相同数量的black节点
RBT Rotation
RBT Deletion
Read Chapter 14 of Introduction to Algorithms (by Thomas H. Cormen, Charles E. Leiserson, and Ronald L. Rivest).
Black-height
- black-height: bh(x)定义为从node x到leave(包括null leave)的任意path上的black node数。
- 最小black-height: a height-h node has black-height ≥ h/2
- 定理: A red-black tree with n internal nodes has height h≤2 log(n+1). (Prove by induction)
时间复杂度
- A red-black tree has O(logn) height.
- Corollary: These operations take O(logn) time:
- Minimum(), Maximum(), Successor(), Predecessor(), Search()
- Insert(), Delete(): but will need special care since they modify tree
可视化
https://www.cs.usfca.edu/~galles/visualization/RedBlack.html
AVL Tree
- AVL是人名: Adelson-Velskii & Landis
- AVL是balance tree. (在所有节点中,右子树的高度与左子树的高度最多相差1)
- AVL被称为第一个自平衡二叉搜索树
AVL height
N(h)=min(#nodes of height h AVL) ⇒ 一个子树的高度至少为h-1,另一个子树的高度至少为h-2。
AVL树的高度约为1.44 log_2n,而红黑树的高度可能高达2 log_2n。因此在AVL中,平均查找速度略快。
Balance factor
Bf = height(Left Subtree) - height(Right Subtree) ∈{-1,0,1}
如果balance factor不在{-1,0,1}范围内就需要进行single rotation或者double rotation操作来使其平衡~
AVL Rotation
Single Rotation
Double Rotation
Right-Left Rotation:
Feft-Right Rotation:
AVL insertion
和BST insertion类似, 但在插入节点后如果tree not balance, 需要通过rotation使其重新平衡. (四种情况: right/left rotation, right-left/left-right rotation)
AVL deletion
和BST deletion类似, 但在删除节点后如果tree not balance, 需要通过(多次)rotation使其重新平衡.
AVL 可视化
https://www.cs.usfca.edu/~galles/visualization/AVLtree.html
Reference
- Chapter 14 of Introduction to Algorithms (by Thomas H. Cormen, Charles E. Leiserson, and Ronald L. Rivest)
- Chapter 10 of Lee K.D., Hubbard S. (2015) Balanced Binary Search Trees. In: Data Structures and Algorithms with Python. Undergraduate Topics in Computer Science. Springer, Cham