Balanced Trees/ Time/Space Tradeoffs-week8

Approaches to Balanced Binary Search Trees平衡树的方法

  • Instance simplification approaches: Self-balancing trees:
    – AVL trees
    – Red-black trees
    – Splay trees
  • Representational changes:
    – 2-3 trees
    – 2-3-4 trees
    – B-trees

8.1 AVL Trees

For a binary (sub-) tree, let the balance factor be the difference between the height of its left sub-tree and that of its right sub-tree.
An AVL tree is a BST in which the balance factor is -1, 0, or 1, for every sub-tree.
主要考察平衡因子,即左右两子数高的差值,AVL tree的每个节点的平衡因子只能是1,0,-1

8.1.1 Building an AVL Tree
15-15 R-Rotation

15-16 L-Rotation

15-17 LR-Rotation

15-18 RL-Rotation
  • 最低的不平衡子数开始re-balance构建AVL tree
  • 在将数组中的数插入AVL tree时,每一步只要不满足平衡就立即rotation,不是等到所有插入结束再调整为AVL
8.1.2 The Single Rotation
15-32

15-33

AVL tree总结
1.t the depth of an AVL tree with n nodes is Θ(log n) .
2.深度为log2(n)
3.在最坏的情况下,搜索最多需要比完美平衡的BST多45%的比较。
4.删除很难实现但插入的复杂度为Θ(log n)

8.1.3 Other Kinds of Balanced Trees

red-black:红黑树是一种BST,它的“平衡”概念略有不同。它的结点是红色或黑色的,所以:

  • 没有红色节点有红色子节点。
  • 从根到边缘的每条路径都有相同数量的黑节点。

最坏情况:最长的路径是最短路径的两倍长

15-47

splay tree:伸展树是一种既能自我调节又能自适应的BST。频繁访问的项更靠近根,因此访问它们的成本更低。

8.2 2-3 Trees

一个树节点存储2-3个项目
BST是一个节点拥有一个项目和最多两个子节点
2-3 tree是一个节点(称为3-node)拥有2个项目和最多3个子节点
2-3-4 tree 是一个节点拥有3个项目和最多4个子节点

15-49

一个节点在拥有三个项目时会拆分,中间的项目promote给父节点,其余两个分割为两个子节点
15-51

15-52

15-53

15-54

2-3 tree 总结
1.最差的搜索时间是当所有节点都是2-nodes时,即二叉树,n=2(h+1)-1
2.最好的搜索时间是当所有节点都是 3-nodes时,n=3(h+1)-1

15-56

8.3Time/Space Tradeoffs -16

用表(增加空间)来减少时间

8.3.1Fibonacci Numbers with Tabulation
16-7
8.3.2Sorting by Counting

找出每个数字的频率并建立对应的索引表

16-29 occ为频率 cumu为累积的值

遍历数组A,在索引表中找到当前数字的最后一个索引,填入数字并将最后一个索引往前移动
16-33

此方法复杂度为Θ(n),不涉及 key-to-key comparison,key-comparison based sorting的复杂度为Ω(nlogn).

8.3.3String Matching-Horspool’s String Search Algorithm

16-59 burte-force

1.建立shift table
16-67 m为pattern的长度

[T A A C G]的shift table为[A T G C]=[2,4,5,1]
若pattern里有相同字母以最小的shift为最终结果
2.运行Horspool’s String Search Algorithm
16-75

16-93 另一种algorithm

16-92 example:shift table为[A B E R]=[4,2,1,3]
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 原文链接: 全网最全的数据结构与算法文章合集 一、时间复杂度 O(n)时间解决的面试题:名人问题O(n)时间解决的...
    passiontim阅读 1,090评论 0 1
  • binary tree二叉树recurrences递归closed forms解析解recursion递归iter...
    葉子_53d1阅读 572评论 0 0
  • 本文为掘金投稿,译文出自:掘金翻译计划 原文地址:Google Interview University 原文作者...
    优质小煤球阅读 475评论 0 0
  • 红黑树和B-tree,是BST(二叉搜索树)里运用较多的两种树, BST category AVL tree 2-...
    wanncy阅读 974评论 0 2
  • Searching remarks: 从bear导入的,不可见图为草稿,重点部分都有写。 Symbol Table...
    gilgamesh09阅读 489评论 0 0