当前位置:   article > 正文

数据结构和算法入门

数据结构和算法入门

1.了解数据结构和算法

1.1 二分查找

        二分查找(Binary Search)是一种在有序数组中查找特定元素的搜索算法。它的基本思想是将数组分成两半,然后比较目标值与中间元素的大小关系,从而确定应该在左半部分还是右半部分继续查找。这个过程不断重复,直到找到目标值或确定它不存在于数组中。

1.1.1 二分查找的实现

(1)循环条件使用 "i <= j" 而不是 "i < j" 是因为,在二分查找的过程中,我们需要同时更新 i 和 j 的值。当 i 和 j 相等时,说明当前搜索范围只剩下一个元素,我们需要检查这个元素是否是我们要找的目标值。如果这个元素不是我们要找的目标值,那么我们可以确定目标值不存在于数组中。

如果我们将循环条件设置为 "i < j",那么当 i 和 j 相等时,我们就无法进入循环来检查这个唯一的元素,这会导致我们无法准确地判断目标值是否存在。

因此,在二分查找的循环条件中,我们应该使用 "i <= j",以确保我们在搜索范围内包含所有可能的元素。

(2)如果你使用 "i + j / 2" 来计算二分查找的中间值,可能会遇到整数溢出的问题。这是因为在 Java 中,整数除法(/)对整数操作时会向下取整,结果仍然是一个整数。例如,如果 ij 都是很大的数,且它们相加结果大于 Integer.MAX_VALUE(即 2^31 - 1),那么直接将它们相加再除以 2 就会导致溢出,因为中间结果已经超出了 int 类型的最大值(会变成负数)。

  1. public static void main(String[] args) {
  2. int[]arr={1,22,33,55,88,99,117,366,445,999};
  3. System.out.println(binarySearch( arr,1));//结果:0
  4. System.out.println(binarySearch( arr,22));//结果:1
  5. System.out.println(binarySearch( arr,33));//结果:2
  6. System.out.println(binarySearch( arr,55));//结果:3
  7. System.out.println(binarySearch( arr,88));//结果:4
  8. System.out.println(binarySearch( arr,99));//结果:5
  9. System.out.println(binarySearch( arr,117));//结果:6
  10. System.out.println(binarySearch( arr,366));//结果:7
  11. System.out.println(binarySearch( arr,445));//结果:8
  12. System.out.println(binarySearch( arr,999));//结果:9
  13. System.out.println(binarySearch( arr,1111));//结果:-1
  14. System.out.println(binarySearch( arr,-1));//结果:-1
  15. }
  16. /**
  17. * @Description
  18. * @Author LY
  19. * @Param [arr, target] 待查找升序数组,查找的值
  20. * @return int 找到返回索引,找不到返回-1
  21. * @Date 2023/12/8 16:38
  22. **/
  23. public static int binarySearch(int[] arr, int target){
  24. //设置 i跟j 初始值
  25. int i=0;
  26. int j= arr.length-1;
  27. //如果i>j,则表示并未找到该值
  28. while (i<=j){
  29. int m=(i+j)>>>1;
  30. // int m=(i+j)/2;
  31. if (target<arr[m]){
  32. //目标在左侧
  33. j=m-1;
  34. }else if(target>arr[m]){
  35. //目标在右侧
  36. i=m+1;
  37. }else{
  38. //相等
  39. return m;
  40. }
  41. }
  42. return -1;
  43. }

 1.1.2 二分查找改动版

        方法 binarySearchAdvanced 是一个优化版本的二分查找算法。它将数组范围从 0 到 arr.length 进行划分(改动1),并且在循环条件中使用 i < j 而不是 i <= j (改动2)。这种修改使得当目标值不存在于数组中时,可以更快地结束搜索。此外,在向左移动右边界时,只需将其设置为中间索引 m 而不是 m - 1 (改动3)。

        这些改动使 binarySearchAdvanced 在某些情况下可能比标准二分查找更快。然而,在实际应用中,这些差异通常很小,因为二分查找本身的复杂度已经很低(O(log n))。

  1. /**
  2. * @return int 找到返回索引,找不到返回-1
  3. * @Description 二分查找改动版
  4. * @Author LY
  5. * @Param [arr, target] 待查找升序数组,查找的值
  6. * @Date 2023/12/8 16:38
  7. **/
  8. public static int binarySearchAdvanced(int[] arr, int target) {
  9. int i = 0;
  10. // int j= arr.length-1;
  11. int j = arr.length;//改动1
  12. // while (i<=j){
  13. while (i < j) {//改动2
  14. int m = (i + j) >>> 1;
  15. if (target < arr[m]) {
  16. // j = m - 1;
  17. j = m; //改动3
  18. } else if (arr[m] < target) {
  19. i = m + 1;
  20. } else {
  21. return m;
  22. }
  23. }
  24. return -1;
  25. }

1.1.3 递归实现

 请查看:3.基础数据结构-链表-CSDN博客        3.5 补充:递归

 1.2 线性查找

        线性查找(Linear Search)是一种简单的搜索算法,用于在无序数组或列表中查找特定元素。它的基本思想是从数组的第一个元素开始,逐一比较每个元素与目标值的大小关系,直到找到目标值或遍历完整个数组。

(1)初始化一个变量 index 为 -1,表示尚未找到目标值。
(2)从数组的第一个元素开始,使用循环依次访问每个元素:
(3)如果当前元素等于目标值,则将 index 设置为当前索引,并结束循环。

(4)返回 index。(如果找到了目标值返回其索引;否则返回 -1 表示未找到目标值)

  1. /**
  2. * @return int 找到返回索引,找不到返回-1
  3. * @Description 线性查找
  4. * @Author LY
  5. * @Param [arr, target] 待查找数组(可以不是升序),查找的值
  6. * @Date 2023/12/8 16:38
  7. **/
  8. public static int LinearSearch(int[] arr, int target) {
  9. int index=-1;
  10. for (int i = 0; i < arr.length; i++) {
  11. if(arr[i]==target){
  12. index=i;
  13. break;
  14. }
  15. }
  16. return index;
  17. }

1.3 衡量算法第一因素

时间复杂度:算法在最坏情况下所需的基本操作次数与问题规模之间的关系。

1.3.1 对比

假设每行代码执行时间都为t,数据为n个,且是最差的执行情况(执行最多次):

二分查找:

二分查找执行时间为:5L+4:
既5*floor(log_2(x)+1)+4
执行语句执行次数
int i=0;1
int j=arr.length-1;1
return -1;1
循环次数为:floor(log_2(n))+1,之后使用L代替
i<=j;L+1
int m= (i+j)>>>1;L
artget<arr[m]L
arr[m]<artgetL
i=m+1;L

线性查找:

线性查找执行时间为:3x+3
执行语句执行次数
int i=0;1
i<a.length;x+1
i++;x
arr[i]==targetx
return -1;1

对比工具:Desmos | 图形计算器

对比结果:

随着数据规模增加,线性查找执行时间会逐渐超过二分查找。

1.3.2 时间复杂度

        计算机科学中,时间复杂度是用来衡量一个算法的执行,随着数据规模增大,而增长的时间成本(不依赖与环境因素)。

时间复杂度的标识:

        假设要出炉的数据规模是n,代码总执行行数用f(n)来表示:

                线性查找算法的函数:f(n)=3*n+3。

                二分查找算法函数::f(n)=5*floor(log_2(x)+1)+4。

为了简化f(n),应当抓住主要矛盾,找到一个变化趋势与之相近的表示法。

1.3.3 渐进上界

渐进上界代表算法执行的最差情况:

        以线性查找法为例:

                f(n)=3*n+3

                g(n)=n

        取c=4,在n0=3后,g(n)可以作为f(n)的渐进上界,因此大O表示法写作O(n)

        以二分查找为例:

                5*floor(log_2(n)+1)+4===》5*floor(log_2(n))+9

                g(n)=log_2(n)

                O(log_2(n))

1.3.4 常见大O表示法

按时间复杂度,从低到高:

(1)黑色横线O(1):常量时间复杂度,意味着算法时间并不随数据规模而变化。

(2)绿色O(log(n)):对数时间复杂度。

(3)蓝色O(n):线性时间复杂度,算法时间与规模与数据规模成正比。

(4)橙色O(n*log(n)):拟线性时间复杂度。

(5)红色O(n^2):平方时间复杂度。

(6)黑色向上O(2^n):指数时间复杂度。

(7)O(n!):这种时间复杂度非常大,通常意味着随着输入规模 n 的增加,算法所需的时间会呈指数级增长。因此,具有 O(n!) 时间复杂度的算法在实际应用中往往是不可行的,因为它们需要耗费大量的计算资源和时间。

1.4 衡量算法第二因素

空间复杂度:与时间复杂度类似,一般也用O衡量,一个算法随着数据规模增大,而增长的额外空间成本。

1.3.1 对比

以二分查找为例:

二分查找占用空间为:4字节
执行语句执行次数
int i=0;4字节
int j=arr.length-1;4字节
int m= (i+j)>>>1;4字节
二分查找占用空间复杂度为:O(1)

性能分析:

        时间复杂度:

                最坏情况:O(log(n))。

                最好情况:待查找元素在数组中央,O(1)。

        空间复杂度:需要常熟个数指针:i,j,m,额外占用空间是O(1)。

1.5 二分查找改进

在之前的二分查找算法中,如果数据在数组的最左侧,只需要执行L次 if 就可以了,但是如果数组在最右侧,那么需要执行L次 if 以及L次 else if,所以二分查找向左寻找元素,比向右寻找元素效率要高。

(1)左闭右开的区间,i指向的可能是目标,而j指向的不是目标。

(2)不在循环内找出,等范围内只剩下i时,退出循环,再循环外比较arr[i]与target。

(3)优点:循环内的平均比较次数减少了。

(4)缺点:时间复杂度:θ(log(n))。

1.6 二分查找相同元素

1.6.1 返回最左侧

当有两个数据相同时,上方的二分查找只会返回中间的元素,而我们想得到最左侧元素就需要对算法进行改进。(Leftmost)

  1. public static void main(String[] args) {
  2. int[] arr = {1, 22, 33, 55, 99, 99, 99, 366, 445, 999};
  3. System.out.println(binarySearchLeftMost1(arr, 99));//结果:4
  4. System.out.println(binarySearchLeftMost1(arr, 999));//结果:9
  5. System.out.println(binarySearchLeftMost1(arr, 998));//结果:-1
  6. }
  7. /**
  8. * @return int 找到相同元素返回返回最左侧查找元素索引,找不到返回-1
  9. * @Description 二分查找LeftMost
  10. * @Author LY
  11. * @Param [arr, target] 待查找升序数组,查找的值
  12. * @Date 2023/12/8 16:38
  13. **/
  14. public static int binarySearchLeftMost1(int[] arr, int target) {
  15. int i = 0;
  16. int j = arr.length - 1;
  17. int candidate = -1;
  18. while (i <= j) {
  19. int m = (i + j) >>> 1;
  20. if (target < arr[m]) {
  21. j = m - 1;
  22. } else if (arr[m] < target) {
  23. i = m + 1;
  24. } else {
  25. // return m; 查找到之后记录下来
  26. candidate=m;
  27. j=m-1;
  28. }
  29. }
  30. return candidate;
  31. }

1.6.2 返回最右侧

当有两个数据相同时,上方的二分查找只会返回中间的元素,而我们想得到最右侧元素就需要对算法进行改进。(Rightmost)

  1. public static void main(String[] args) {
  2. int[] arr = {1, 22, 33, 55, 99, 99, 99, 366, 445, 999};
  3. System.out.println(binarySearchRightMost1(arr, 99));//结果:6
  4. System.out.println(binarySearchRightMost1(arr, 999));//结果:9
  5. System.out.println(binarySearchRightMost1(arr, 998));//结果:-1
  6. }
  7. /**
  8. * @return int 找到相同元素返回返回最右侧侧查找元素索引,找不到返回-1
  9. * @Description 二分查找RightMost
  10. * @Author LY
  11. * @Param [arr, target] 待查找升序数组,查找的值
  12. * @Date 2023/12/8 16:38
  13. **/
  14. public static int binarySearchRightMost1(int[] arr, int target) {
  15. int i = 0;
  16. int j = arr.length - 1;
  17. int candidate = -1;
  18. while (i <= j) {
  19. int m = (i + j) >>> 1;
  20. if (target < arr[m]) {
  21. j = m - 1;
  22. } else if (arr[m] < target) {
  23. i = m + 1;
  24. } else {
  25. // return m; 查找到之后记录下来
  26. candidate=m;
  27. i = m + 1;
  28. }
  29. }
  30. return candidate;
  31. }

1.6.3 优化

将leftMost优化后,可以在未找到目标值的情况下,返回大于等于目标值最靠左的一个索引。

  1. /**
  2. * @return int 找到相同元素返回返回最左侧查找元素索引,找不到返回i
  3. * @Description 二分查找LeftMost
  4. * @Author LY
  5. * @Param [arr, target] 待查找升序数组,查找的值
  6. * @Date 2023/12/8 16:38
  7. **/
  8. public static int binarySearchLeftMost2(int[] arr, int target) {
  9. int i = 0;
  10. int j = arr.length - 1;
  11. while (i <= j) {
  12. int m = (i + j) >>> 1;
  13. if (target <= arr[m]) {
  14. j = m - 1;
  15. } else {
  16. i = m + 1;
  17. }
  18. }
  19. return i;
  20. }

将rightMost优化后,可以在未找到目标值的情况下,返回小于等于目标值最靠右的一个索引。

1.6.4 应用场景

1.6.4.1 查排名

(1)查找排名:
        在执行二分查找时,除了返回目标值是否存在于数组中,还可以记录查找过程中遇到的目标值的位置。如果找到了目标值,则直接返回该位置作为排名;如果没有找到目标值,但知道它应该插入到哪个位置才能保持数组有序,则可以返回这个位置作为排名。

         leftMost(target)+1
(2)查找前任(前驱):
        如果目标值在数组中存在,并且不是数组的第一个元素,那么其前任就是目标值左边的一个元素。我们可以在找到目标值之后,再调用一次二分查找函数,这次查找的目标值设置为比当前目标值小一点的数。这样就可以找到目标值左侧最接近它的元素,即前任。

         leftMost(target)-1
(3)查找后任(后继):
        如果目标值在数组中存在,并且不是数组的最后一个元素,那么其后任就是目标值右边的一个元素。类似地,我们可以在找到目标值之后,再调用一次二分查找函数,这次查找的目标值设置为比当前目标值大一点的数。这样就可以找到目标值右侧最接近它的元素,即后任。

         rightMost(target)+1

(3)最近邻居:

        前任和后任中,最接近目标值的一个元素。

1.6.4.2 条件查找元素

(1)小于某个值:0 ~ leftMost(target)-1

(2)小于等于某个值:0 ~ rightMost(target)

(3)大于某个值:rightMost(target)+1 ~ 无穷大

(4)大于等于某个值:leftMost(4) ~ 无穷大

(5)他们可以组合使用。

 2. 基础数据结构-数组

2.1 概念

        数组是一种数据结构,它是一个由相同类型元素组成的有序集合。在编程中,数组的定义是创建一个具有特定大小和类型的存储区域来存放多个值。数组可以是一维、二维或多维的。每个元素至少有一个索引或键来标识。

 2.2 数组特点

(1)固定大小:数组的大小在创建时就被确定下来,并且不能在后续操作中更改。这意味着一旦创建了数组,就不能添加或删除元素(除非使用新的数组来替换旧的数组)。
(2)相同数据类型:数组中的所有元素必须是同一数据类型的。例如,一个整数数组只能存储整数,而不能混杂着字符串或其他类型的数据。
(3)连续内存空间:数组中的元素在内存中是连续存放的。
(4)索引访问:数组元素是通过索引来访问的,索引通常从0开始。因此,第一个元素的索引是0,第二个元素的索引是1,以此类推。
(5)高效的随机访问:由于数组元素在内存中是连续存放的,所以可以快速地通过索引访问到任何一个元素,时间复杂度为O(1)。
(6)有序性:虽然数组本身并没有规定其元素必须按照特定顺序排列,但通常在编程中会把数组看作是有序的数据结构,因为它的元素是按索引顺序存储的。
(7)可变性:数组中元素值是可改变的,只要该元素的数据类型与数组元素类型兼容即可。
(8)一维、二维或多维:数组可以是一维的(即线性的),也可以是二维或多维的。多维数组通常用于表示表格数据或其他复杂的网格结构。

这些特性使得数组在许多场景下非常有用,尤其是在需要对大量同类型数据进行高效访问和处理的时候。

2.3 数组特点(扩展)

2.3.1 数组的存储

        因为数组中的元素在内存中是连续存放的。这意味着可以通过计算每个元素相对于数组开始位置的偏移量来访问它们,从而提高访问速度。 数组起始地址为BaseAddress,可以使用公式BaseAddress+ i *size,计算出索引 i 元素的地址,i 即是索引,java和C等语言中,都是从0开始。size是每个元素占用的字节,例如int占用4字节,double占用8字节。

        因此,数组的随机访问和数据规模无关,时间复杂度为O(1)。

2.3.2 空间占用

JAVA的数组结构包含:markword(8字节),class指针(4字节),数组大小(4字节)。

(1)数组本身是一个对象。每个Java对象都有一个对象头(Object Header),其中包含了类指针和Mark Word等信息。。Mark Word是HotSpot虚拟机设计的一种数据结构,用于存储对象的运行时元数据。

(2)Mark Word的作用主要包括:

        (2.1)对象的锁状态:Mark Word中的部分内容会根据对象是否被锁定而改变。例如,如果数组正在被synchronized同步块或方法保护,那么这部分内容将包含有关锁的信息,如线程ID、锁状态等。
        (2.2)垃圾收集信息:Mark Word还存储了与垃圾收集相关的信息,如对象的分代年龄和类型指针等。这对于垃圾收集器跟踪和回收对象非常关键。
其他标志位:除此之外,Mark Word可能还包括一些其他的标志位,如偏向锁标志、轻量级锁标志等。
        (2.3)需要注意的是,由于Mark Word是为整个对象服务的,所以它并不直接针对数组元素。数组元素的数据是存储在对象头之后的实例数据区域中。Mark Word主要是为了支持JVM进行各种操作,比如内存管理和并发控制等。

(3)类指针:类指针指向的是该对象所属的类元数据(Class Metadata)。这个指针对于运行时的动态绑定、方法调用以及反射操作非常重要。它存储了关于对象类型的所有信息,包括类名、父类、接口、字段、方法、常量池等。在64位JVM上,类指针通常占用8字节。而在32位JVM上,类指针占用4字节。

(4)数组大小:数组大小为4字节,因此决定了数组最大容量为2^32,数组元素+字节对齐(JAVA中所有对象的大小都是8字节的整数倍,不足的要用对齐字节补足)

例如:

int [] arr={1,2,3,4,5}

该数组包含内容包括:

单位(字节)

markword(8)
class指针(4)数组大小(4)
1(4)2(4)
3(4)4(4)
5(4)字节对齐(4)

大小为:8+4+4+4*4+4+4=40字节

2.3.3 动态数组

        因为数组的大小是固定的,所以数组中的元素并不能随意地添加和删除。这种数组称之为静态数组。

        JAVA中的ArrayList是已经创建好的动态数组。

插入或者删除性能时间复杂度:

        头部位置:O(n)

        中间位置:O(n)

        尾部位置:O(1) 均摊来说

  1. package org.alogorithm;
  2. import java.util.Arrays;
  3. import java.util.Iterator;
  4. import java.util.function.Consumer;
  5. import java.util.stream.IntStream;
  6. public class Main02 {
  7. public static void main(String[] args) {
  8. MyArray myArray = new MyArray();
  9. myArray.addLast(1);
  10. myArray.addLast(2);
  11. myArray.addLast(3);
  12. myArray.addLast(4);
  13. myArray.addLast(5);
  14. myArray.addLast(7);
  15. myArray.addLast(8);
  16. myArray.addLast(9);
  17. myArray.addLast(10);
  18. myArray.addLast(11);
  19. /*for (int i = 0; i < myArray.size; i++) {
  20. System.out.println(myArray.array[i]);
  21. }*/
  22. myArray.foreach((e) -> {
  23. //具体操作由调用方界定
  24. System.out.println(e + "Consumer");
  25. });
  26. myArray.add(2, 6);
  27. for (Integer integer : myArray) {
  28. System.out.println(integer + "Iterable");
  29. }
  30. System.out.println(myArray.remove(4)+"元素被删除");
  31. myArray.stream().forEach(e -> {
  32. System.out.println(e + "stream");
  33. });
  34. }
  35. static class MyArray implements Iterable<Integer> {
  36. private int size = 0;//逻辑大小
  37. private int capacity = 8;//容量
  38. private int[] array = {};
  39. public void addLast(int value) {
  40. /*array[size] = value;
  41. size++;*/
  42. add(size, value);
  43. }
  44. public void add(int index, int value) {
  45. //容量不够扩容
  46. checkAndGrow();
  47. /*
  48. * param1 :要copy的数组
  49. * param1 :copy的起始位置
  50. * param1 :要存放数组
  51. * param1 :要copy的个数
  52. * 这个方法表示要将array从index开始copy到index+1的位置,
  53. * copy的个数是数组的大小-index(index向后的元素)
  54. * */
  55. if (index >= 0 && index <= size) {
  56. System.arraycopy(array, index, array, index + 1, size - index);
  57. }
  58. //合并add方法
  59. array[index] = value;
  60. size++;
  61. }
  62. private void checkAndGrow() {
  63. if (size==0){
  64. array=new int[capacity];
  65. }else if (size == capacity) {
  66. capacity+=capacity>>1;
  67. int[] newArray = new int[capacity];
  68. //赋值数组
  69. System.arraycopy(array,0,newArray,0,size);
  70. array=newArray;
  71. }
  72. }
  73. //查询元素
  74. public int get(int index) {
  75. return array[index];
  76. }
  77. //遍历数组 1
  78. //查询元素
  79. public void foreach(Consumer<Integer> consumer) {
  80. for (int i = 0; i < size; i++) {
  81. //System.out.println(array[i]);
  82. //提供array[i],不需要返回值
  83. consumer.accept(array[i]);
  84. }
  85. }
  86. //遍历数组2 迭代器模式
  87. @Override
  88. public Iterator<Integer> iterator() {
  89. //匿名内部类
  90. return new Iterator<Integer>() {
  91. int i = 0;
  92. @Override
  93. public boolean hasNext() {
  94. //有没有下一个元素
  95. return i < size;
  96. }
  97. @Override
  98. public Integer next() {
  99. //返回当前元素,并将指针移向下一个元素
  100. return array[i++];
  101. }
  102. };
  103. }
  104. //遍历数组3 数据流
  105. public IntStream stream() {
  106. return IntStream.of(Arrays.copyOfRange(array, 0, size));
  107. }
  108. public int remove(int index) {
  109. int removeed = array[index];
  110. System.arraycopy(array, index + 1, array, index, size - index - 1);
  111. size--;
  112. return removeed;
  113. }
  114. }
  115. }

2.4 二维数组

(1)二维数组占32个字节,其中array[0],array[1],array[2]元素分别保存了指向三个一维数组的引用。

(2)三个一维数组各占40个字节。

(3)他们在内存布局上是连续的。

  1. package org.alogorithm.array;
  2. public class Main03 {
  3. public static void main(String[] args) {
  4. int rows = 1_000_000;
  5. int columns = 14;
  6. int[][] arr = new int[rows][columns];
  7. long ijStar = System.currentTimeMillis();
  8. ij(arr, rows, columns);
  9. long ijEnd = System.currentTimeMillis();
  10. System.out.println("ij执行时间为:"+(ijEnd-ijStar));//ij执行时间为:10
  11. long jiStar = System.currentTimeMillis();
  12. ji(arr, rows, columns);
  13. long jiEnd = System.currentTimeMillis();
  14. System.out.println("ji执行时间为:"+(jiEnd-jiStar));//ji执行时间为:47
  15. }
  16. public static void ji(int[][] arr, int rows, int columns) {
  17. int sum = 0;
  18. for (int j = 0; j < columns; j++) {
  19. for (int i = 0; i < rows; i++) {
  20. sum += arr[i][j];
  21. }
  22. }
  23. System.out.println(sum+"ji");
  24. }
  25. public static void ij(int[][] arr, int rows, int columns) {
  26. int sum = 0;
  27. for (int i = 0; i < rows; i++) {
  28. for (int j = 0; j < columns; j++) {
  29. sum += arr[i][j];
  30. }
  31. }
  32. System.out.println(sum+"ij");
  33. }
  34. }

        在计算机中,内存是分块存储的。每个内存块称为一个页(page)。当程序访问数组时,CPU会从内存中加载包含该元素所在的整个页面到高速缓存(cache)中。

在这个例子中,ij和ji两个方法的主要区别在于它们遍历数组的方式:

        ij按行遍历数组:它首先遍历所有的行,然后在同一行内遍历列。
        ji按列遍历数组:它先遍历所有的列,然后在同一列内遍历行。
由于现代计算机体系结构的设计特点,ij比ji更快的原因有以下几点:

        (1)缓存局部性(Cache Locality):按行遍历数组时,相邻的元素在物理内存中彼此靠近,这使得CPU可以高效地利用缓存来加速数据访问。这是因为通常情况下,一次内存读取操作将加载一整块数据(通常是64字节),如果这一块数据中的多个元素被连续使用,那么这些元素很可能都在同一块缓存中,从而减少了对主内存的访问次数。
        (2)预取(Prefetching):一些现代处理器具有预取机制,可以预测接下来可能需要的数据并提前将其加载到缓存中。按照行顺序遍历数组时,这种机制更有可能发挥作用,因为相邻的元素更可能在未来被访问。
综上所述,ij的遍历方式更适合计算机硬件的工作原理,因此执行速度更快。

 3 基础数据结构-链表

3.1 定义

        链表(Linked List)是一种线性数据结构,由一系列节点(Node)组成。每个节点包含两部分:元素值(Element Value)和指向下一个节点的指针(Pointer)。链表可以分为多种类型,如单向链表、双向链表、循环链表等。元素在存储上并不连续。

 3.1.1 分类

(1)单向链表:每个元素只知道下一个元素。

(2)双向链表:每个元素知道下一个元素和上一个元素。

(3)循环链表:通常的链表为节点tail指向null,但是循环链表的tail指向head。

 3.1.2 哨兵节点

链表内还有一种特殊的节点,成为哨兵(Sentinel)节点,也叫做哑元(Dummy)节点,他并不存储数据,用来减缓别介判断。

3.2 性能

随机访问:

        根据index查找,时间复杂度O(n)。

插入或者删除:

        起始位置:O(1)。

        结束位置:如果已知tail为节点是O(1),否则为O(n)。

        中间位置:根据index查找时间+O(1)。

3.3 单向链表

单向链表的主要操作包括:

        插入节点:在链表的特定位置插入一个新的节点。
        删除节点:从链表中删除一个特定的节点。
        查找节点:在链表中查找一个特定的节点。
        遍历链表:从头到尾访问链表中的每个节点。
单向链表的优点包括:

        动态性:可以随时添加或删除节点,不需要预先知道数据的数量和大小。
        效率:插入和删除操作通常只需要常数时间。
缺点包括:

        访问速度:访问链表中的特定元素需要从头开始遍历,时间复杂度为O(n)。
        空间效率:每个节点都需要额外的空间来存储指针。

3.3.1 普通单向链表实现

  1. package org.alogorithm.linkedList;
  2. import java.util.Iterator;
  3. import java.util.function.Consumer;
  4. public class SingLinkListMain {
  5. public static void main(String[] args) {
  6. SingLinkList singLinkList = new SingLinkList();
  7. singLinkList.addFirst(1);
  8. singLinkList.addFirst(2);
  9. singLinkList.addFirst(3);
  10. singLinkList.addFirst(4);
  11. singLinkList.addFirst(5);
  12. //使用Consumer+while实现
  13. singLinkList.consumerLoop1(value -> System.out.println(value + "while,"));
  14. System.out.println("----------------------------------------");
  15. singLinkList.addLast(99);//尾部添加一个元素
  16. singLinkList.addLast(100);//尾部添加一个元素
  17. //使用Consumer+for实现
  18. singLinkList.consumerLoop2(value -> System.out.println(value + "for"));
  19. System.out.println("----------------------------------------");
  20. int res = singLinkList.get(3);
  21. System.out.println("查询结果为" + res);
  22. singLinkList.insert(0, 111);
  23. singLinkList.insert(3, 111);
  24. //使用迭代器实现
  25. for (Integer integer : singLinkList) {
  26. System.out.println(integer + "iterable");
  27. }
  28. System.out.println("----------------------------------------");
  29. /*int reserr = singLinkList.get(100);
  30. System.out.println("查询结果为"+reserr);*/
  31. // singLinkList.removeFirst();//删除第一个节点
  32. singLinkList.reomve(0);
  33. singLinkList.reomve(3);
  34. singLinkList.reomve(99);
  35. //使用递归
  36. singLinkList.recursionLoop(e -> {
  37. System.out.println(e + "recursion");
  38. }, singLinkList.head);
  39. // System.out.println(singLinkList.findLast());
  40. }
  41. }
  42. //单向链表
  43. class SingLinkList implements Iterable<Integer> {
  44. // head指针
  45. Node head;
  46. //删除指定索引节点
  47. public void reomve(int index) {
  48. if (index < 0) {
  49. IndexOutOfBoundsException(head, "索引不能为负");
  50. } else if (index == 0) {
  51. removeFirst();
  52. }
  53. Node node = findNode(index);//当前个节点
  54. IndexOutOfBoundsException(node, "当前节点为空");
  55. Node beforNode = findNode(index - 1);//上一个节点
  56. beforNode.next = node.next;
  57. }
  58. //删除第一个节点
  59. public void removeFirst() {
  60. IndexOutOfBoundsException(head, "链表为空无");
  61. head = head.next;//将head设置为之前的head.next第二个节点
  62. }
  63. //向索引位置添加一个元素
  64. public void insert(int index, int value) {
  65. Node afterNode = findNode(index);//后一个节点
  66. //构建新的节点
  67. Node newNode = new Node(value, afterNode);
  68. if (index == 0) {
  69. //索引为0向头部添加
  70. addFirst(value);
  71. } else {
  72. Node beforNode = findNode(index - 1);
  73. //否则将befor的next属性设置为当前节点
  74. IndexOutOfBoundsException(beforNode, "索引位置异常");
  75. beforNode.next = newNode;
  76. }
  77. }
  78. //抛出异常
  79. private static void IndexOutOfBoundsException(Node beforNode, String msg) {
  80. if (beforNode == null) {
  81. throw new IndexOutOfBoundsException(msg);
  82. }
  83. }
  84. //获取节点的值
  85. public int get(int index) {
  86. Node node = findNode(index);
  87. IndexOutOfBoundsException(node, "索引位置异常");
  88. return node.value;
  89. }
  90. //获取索引的元素
  91. private Node findNode(int index) {
  92. Node point = head;
  93. int i = 0;
  94. while (point != null) {
  95. if (i == index) {
  96. return point;
  97. } else {
  98. point = point.next;
  99. i++;
  100. }
  101. }
  102. return null;
  103. }
  104. //向最后添加一个元素
  105. public void addLast(int value) {
  106. Node last = findLast();//找到最后一个节点
  107. if (last == null) {
  108. //没有最后一个就添加第一个
  109. addFirst(value);
  110. } else {
  111. //否则设置最有一个节点的next属性为新的Node
  112. last.next = new Node(value, null);
  113. }
  114. }
  115. //查找最后一个元素
  116. public Node findLast() {
  117. Node point = head;
  118. if (head == null) {
  119. return null;
  120. }
  121. while (true) {
  122. if (point.next != null) {
  123. point = point.next;
  124. } else {
  125. return point;
  126. }
  127. }
  128. }
  129. //头部添加一个元素
  130. public void addFirst(int value) {
  131. //链表为空
  132. // head = new Node(value,null);
  133. //链表非空
  134. head = new Node(value, head);//链表为空时head就是null
  135. }
  136. public void recursionLoop(Consumer<Integer> consumer, Node point) {
  137. if (point != null) {
  138. consumer.accept(point.value); // 先输出当前节点的值
  139. recursionLoop(consumer, point.next); // 再递归处理下一个节点
  140. }
  141. }
  142. //迭代器遍历
  143. @Override
  144. public Iterator<Integer> iterator() {
  145. return new Iterator<Integer>() {
  146. Node point = head;
  147. @Override
  148. public boolean hasNext() {
  149. return point != null;
  150. }
  151. @Override
  152. public Integer next() {
  153. int value = point.value;
  154. point = point.next;
  155. return value;
  156. }
  157. };
  158. }
  159. //循环遍历 for
  160. public void consumerLoop2(Consumer<Integer> consumer) {
  161. for (Node point = head; point != null; point = point.next) {
  162. consumer.accept(point.value);
  163. }
  164. }
  165. //循环遍历 while
  166. public void consumerLoop1(Consumer<Integer> consumer) {
  167. Node point = head;
  168. while (point != null) {
  169. consumer.accept(point.value);
  170. point = point.next;
  171. }
  172. }
  173. //节点
  174. private static class Node {
  175. int value;//值
  176. Node next;//下一个节点
  177. public Node(int value, Node next) {
  178. this.value = value;
  179. this.next = next;
  180. }
  181. }
  182. }

这是一个普通单向链表的全部功能实现,但是实现起来比较麻烦。

补充:关于类需不需要带static:

        (1)Node内部类可以添加static关键字,这是因为Java允许在类中定义静态成员。将内部类声明为静态的,意味着它不再依赖于外部类的实例。

        (2)静态内部类不能访问外部类的非静态成员(包括字段和方法)。
        (3)由于不依赖外部类实例,创建静态内部类的对象不需要外部类对象。

3.3.2 单向链表-带哨兵

加入哨兵之后,就不存在head为空的情况,也不存在链表为空,某个节点上一个元素为空,插入头部时链表为空的情况,但是对应的循环遍历要从head.next开始,可以简化很多代码。

  1. public class SingLinkSentryListMain {
  2. public static void main(String[] args) {
  3. SingLinkSentryList singLinkSentryList = new SingLinkSentryList();
  4. singLinkSentryList.addLast(69);
  5. singLinkSentryList.addLast(70);
  6. //使用Consumer+while实现
  7. singLinkSentryList.consumerLoop1(value -> System.out.println(value + "while,"));
  8. System.out.println(singLinkSentryList.get(0));
  9. //System.out.println(singLinkSentryList.get(99));
  10. singLinkSentryList.insert(0,99);
  11. // singLinkSentryList.insert(99,99);
  12. System.out.println("----------------------------------------");
  13. //使用Consumer+for实现
  14. singLinkSentryList.consumerLoop2(value -> System.out.println(value + "for"));
  15. System.out.println("----------------------------------------");
  16. singLinkSentryList.reomve(1);
  17. singLinkSentryList.reomve(0);
  18. // singLinkSentryList.reomve(99);
  19. //使用迭代器实现
  20. for (Integer integer : singLinkSentryList) {
  21. System.out.println(integer + "iterable");
  22. }
  23. System.out.println("----------------------------------------");
  24. //使用递归
  25. /* singLinkSentryList.recursionLoop(e -> {
  26. System.out.println(e + "recursion");
  27. }, singLinkSentryList.head);*/
  28. }
  29. }
  30. //单向链表
  31. class SingLinkSentryList implements Iterable<Integer> {
  32. // head指针
  33. Node head=new Node(1,null);//头指针指向哨兵
  34. //删除指定索引节点
  35. public void reomve(int index) {
  36. if (index < 0) {
  37. IndexOutOfBoundsException(head, "索引不能为负");
  38. }
  39. Node node = findNode(index);//当前个节点
  40. IndexOutOfBoundsException(node, "当前节点为空");
  41. Node beforNode = findNode(index - 1);//上一个节点
  42. beforNode.next = node.next;
  43. }
  44. //删除第一个节点
  45. public void removeFirst() {
  46. IndexOutOfBoundsException(head, "链表为空无");
  47. reomve(0);
  48. }
  49. //向索引位置添加一个元素
  50. public void insert(int index, int value) {
  51. Node afterNode = findNode(index);//后一个节点
  52. //构建新的节点
  53. Node newNode = new Node(value, afterNode);
  54. Node beforNode = findNode(index - 1);
  55. //否则将befor的next属性设置为当前节点
  56. IndexOutOfBoundsException(beforNode, "索引位置异常");
  57. beforNode.next = newNode;
  58. }
  59. //抛出异常
  60. private static void IndexOutOfBoundsException(Node beforNode, String msg) {
  61. if (beforNode == null) {
  62. throw new IndexOutOfBoundsException(msg);
  63. }
  64. }
  65. //获取节点的值
  66. public int get(int index) {
  67. Node node = findNode(index);
  68. IndexOutOfBoundsException(node, "索引位置异常");
  69. return node.value;
  70. }
  71. //获取索引的元素
  72. private Node findNode(int index) {
  73. Node point = head;
  74. int i = -1;
  75. while (point != null) {
  76. if (i == index) {
  77. return point;
  78. } else {
  79. point = point.next;
  80. i++;
  81. }
  82. }
  83. return null;
  84. }
  85. //向最后添加一个元素
  86. public void addLast(int value) {
  87. Node last = findLast();//因为有哨兵,head不可能为空
  88. last.next = new Node(value, null);
  89. }
  90. //查找最后一个元素
  91. public Node findLast() {
  92. Node point = head;
  93. while (true) {
  94. if (point.next != null) {
  95. point = point.next;
  96. } else {
  97. return point;
  98. }
  99. }
  100. }
  101. //头部添加一个元素
  102. public void addFirst(int value) {
  103. insert(0,value);
  104. }
  105. public void recursionLoop(Consumer<Integer> consumer, Node point) {
  106. if (point != null) {
  107. consumer.accept(point.value); // 先输出当前节点的值
  108. recursionLoop(consumer, point.next); // 再递归处理下一个节点
  109. }
  110. }
  111. //迭代器遍历
  112. @Override
  113. public Iterator<Integer> iterator() {
  114. return new Iterator<Integer>() {
  115. Node point = head.next;
  116. @Override
  117. public boolean hasNext() {
  118. return point != null;
  119. }
  120. @Override
  121. public Integer next() {
  122. int value = point.value;
  123. point = point.next;
  124. return value;
  125. }
  126. };
  127. }
  128. //循环遍历 for
  129. public void consumerLoop2(Consumer<Integer> consumer) {
  130. for (Node point = head.next; point != null; point = point.next) {
  131. consumer.accept(point.value);
  132. }
  133. }
  134. //循环遍历 while
  135. public void consumerLoop1(Consumer<Integer> consumer) {
  136. Node point = head.next;
  137. while (point != null) {
  138. consumer.accept(point.value);
  139. point = point.next;
  140. }
  141. }
  142. //节点
  143. private static class Node {
  144. int value;//值
  145. Node next;//下一个节点
  146. public Node(int value, Node next) {
  147. this.value = value;
  148. this.next = next;
  149. }
  150. }
  151. }

3.4 双向链表

双向链表相比单向链表有以下优势:

        双向访问:在双向链表中,每个节点都有两个指针,一个指向前一个节点(前驱),一个指向后一个节点(后继)。这使得在遍历或操作链表时可以向前或向后移动,提供了更大的灵活性。在某些情况下,这种双向访问能力可以简化算法并提高效率。
        更方便的插入和删除操作:虽然在双向链表中插入和删除节点需要更新两个相邻节点的指针,但有时这反而能更快地完成操作。例如,如果已知要删除的节点,那么可以直接通过其前驱节点进行删除,无需从头开始查找。
        更高效的搜索和定位:在某些搜索和定位操作中,双向链表的优势更加明显。例如,如果要查找某个特定节点的前驱节点,单向链表需要从头开始遍历,而双向链表可以直接通过当前节点访问其前驱节点。

        尾节点操作:对尾结点操作更加方便而不用遍历查找到最后一个节点。
双向链表缺点:
        空间开销:每个节点在单向链表的基础上都需要额外的空间来存储指向前一个节点的指针。
        操作复杂性:在插入和删除节点时,需要更新两个相邻节点的指针,这在一定程度上增加了操作的复杂性。

3.4.1 双向链表-带哨兵

  1. package org.alogorithm.linkedList;
  2. import java.util.Iterator;
  3. /**
  4. * 双向链表(带哨兵)
  5. **/
  6. public class DoubleLinkedListMain {
  7. public static void main(String[] args) {
  8. DoubleLinkedList doubleLinkedList = new DoubleLinkedList();
  9. doubleLinkedList.addFirst( 1);
  10. doubleLinkedList.add(1, 2);
  11. doubleLinkedList.add(2, 3);
  12. doubleLinkedList.add(3, 4);
  13. System.out.println("-------------add-----------------");
  14. for (Integer integer : doubleLinkedList){
  15. System.out.println(integer);
  16. }
  17. doubleLinkedList.remove(2);
  18. System.out.println("-------------remove-----------------");
  19. for (Integer integer : doubleLinkedList){
  20. System.out.println(integer);
  21. }
  22. doubleLinkedList.addLast(20);
  23. System.out.println("-----------addLast------------------");
  24. for (Integer integer : doubleLinkedList){
  25. System.out.println(integer);
  26. }
  27. doubleLinkedList.remove(1);
  28. System.out.println("-------remove---------------------");
  29. for (Integer integer : doubleLinkedList){
  30. System.out.println(integer);
  31. }
  32. doubleLinkedList.removeLast();
  33. System.out.println("----------removeLast-------------------");
  34. for (Integer integer : doubleLinkedList){
  35. System.out.println(integer);
  36. }
  37. }
  38. }
  39. class DoubleLinkedList implements Iterable<Integer>{
  40. private Node head;//头部哨兵
  41. private Node tail;//尾部哨兵
  42. public DoubleLinkedList() {
  43. head = new Node(null, 0, null);//头哨兵赋值
  44. tail = new Node(head, 0, null);//尾哨兵赋值
  45. head.next = tail;
  46. }
  47. //操作尾节点
  48. public void removeLast(){
  49. Node node = tail.prev;//要删除的节点
  50. if(node==head){
  51. IndexOutOfBoundsException(head.prev,"当前链表为空");
  52. }
  53. Node prevNode = node.prev;//上一个节点
  54. prevNode.next=tail;//上一个节点的next指向为哨兵
  55. tail.prev=prevNode;//尾哨兵的prev的像一个节点为prevNode
  56. }
  57. public void addLast(int value){
  58. Node lastNode = tail.prev;//原本最后一个节点
  59. Node node = new Node(lastNode, value, tail);
  60. lastNode.next=node;//原本节点下一个节点指向当前节点
  61. tail.prev=node;//尾哨兵上一个节点设置为当前节点
  62. }
  63. public void removeFirst() {
  64. remove(0);
  65. }
  66. public void remove(int index) {
  67. Node prevNode = findNode(index - 1);//上一个节点
  68. IndexOutOfBoundsException(prevNode, "非法指针,指针异常");
  69. Node node = prevNode.next;//待删除节点
  70. IndexOutOfBoundsException(node, "非法指针,待删除节点为空");
  71. Node nextNode = node.next;//下一个节点
  72. prevNode.next = nextNode;//上一个节点的next指针指向nextNode
  73. nextNode.prev = prevNode;//下一个节点的prev指针指向prevNode
  74. }
  75. public void addFirst(int value) {
  76. add(0, value);
  77. }
  78. //根据索引插入值
  79. public void add(int index, int value) {
  80. Node prevNode = findNode(index - 1);//查找原本节点
  81. IndexOutOfBoundsException(prevNode, "非法指针,指针异常");
  82. Node next = prevNode.next;
  83. Node newNode = new Node(prevNode, value, next);//设置prev节点为oldNode的prev节点,next节点为oldNode节点
  84. prevNode.next = newNode;//设置前节点的后一个节点为当前节点
  85. next.prev = newNode;//设置oldNode的上一个节点为当前节点
  86. }
  87. //查找索引对应的节点
  88. public Node findNode(int index) {
  89. int i = -1;
  90. //当p不是尾哨兵时循环继续
  91. for (Node p = head; p != tail; p = p.next, i++) {
  92. if (i == index) {
  93. return p;
  94. }
  95. }
  96. return null;
  97. }
  98. //抛出异常
  99. private static void IndexOutOfBoundsException(Node node, String msg) {
  100. if (node == null) {
  101. throw new IndexOutOfBoundsException(msg);
  102. }
  103. }
  104. @Override
  105. public Iterator<Integer> iterator() {
  106. return new Iterator<Integer>() {
  107. //设置起始指针
  108. Node p = head.next;
  109. @Override
  110. public boolean hasNext() {
  111. return p!= tail;
  112. }
  113. @Override
  114. public Integer next() {
  115. int value=p.value;
  116. p=p.next;
  117. return value;
  118. }
  119. };
  120. }
  121. static class Node {
  122. Node prev;//上一个节点指针
  123. int value;//值
  124. Node next;//下一个节点指针
  125. public Node(Node prev, int value, Node next) {
  126. this.prev = prev;
  127. this.value = value;
  128. this.next = next;
  129. }
  130. }
  131. }

3.6环形链表

        环形链表,也称为循环链表,是一种特殊的链表数据结构。在环形链表中,最后一个节点的指针不再指向空(NULL),而是指向链表中的某个节点,通常是头节点,形成一个环状结构。

以下是对环形链表的主要特性和操作的描述:

特性:        结构:环形链表可以是单向的或双向的。在单向环形链表中,每个节点包含一个指针指向下一个节点;在双向环形链表中,每个节点包含两个指针,一个指向前一个节点,一个指向后一个节点(head节点既作为头也作为尾)。
        环:链表的最后一个节点的指针不指向空,而是指向链表中的另一个节点,形成了一个环。这意味着从任何节点开始遍历,如果不做特殊处理,将会无限循环下去。
        遍历:由于环的存在,普通遍历方法(如递归或迭代)如果不做特殊处理,将无法自然地终止。

3.5.1 双向环形链表

3.7 不同链表的特性

单向链表:

        结构:每个节点包含一个指针,指向下一个节点。
        访问:只能从头节点开始向尾节点进行单向遍历。
        插入和删除操作:需要从头节点或已知的节点开始查找目标位置,操作相对复杂。
        空间复杂性:每个节点只需要存储一个指向下一个节点的指针,空间开销较小。
        应用场景:适用于不需要频繁修改且对空间效率要求较高的场景。
双向链表:

        结构:每个节点包含两个指针,一个指向前一个节点(前驱),一个指向后一个节点(后继)。
        访问:可以双向访问,即可以从头节点遍历到尾节点,也可以从尾节点反向遍历到头节点。
        插入和删除操作:在已知要插入或删除节点的前后节点时,操作更快,因为可以直接通过前驱或后继节点进行修改。
        空间复杂性:每个节点需要额外的空间来存储前驱和后继指针,所以空间开销比单向链表大。
        应用场景:适用于需要频繁双向访问、搜索和定位操作的场景。
双向循环链表:

        结构:类似于双向链表,但尾节点的后继指针指向头节点,而头节点的前驱指针指向尾节点,形成一个环状结构。
        访问:可以双向无限循环访问,从任意节点开始都可以遍历整个链表。
        插入和删除操作:与双向链表类似,但在处理首尾节点的操作时需要特殊处理,确保环的完整性。
        空间复杂性:与双向链表相同,每个节点需要额外的空间来存储前驱和后继指针。
        应用场景:适用于需要循环遍历、模拟环形数据结构或者需要在到达链表尾部后自动返回头部的场景。

 4.基础数据结构-队列

4.1 概述

       队列是一种基础且广泛应用的线性数据结构,它模拟了现实生活中的排队现象,遵循“先进先出”(First-In-First-Out, FIFO)原则。在队列中,元素的添加和移除遵循特定的顺序:

       入队操作(Enqueue):新元素被添加到队列的尾部(称为队尾或rear),意味着最近到达的元素将排在队列的末尾等待处理。

       出队操作(Dequeue):从队列的头部(称为队头或front)移除元素,确保最先到达的元素最先离开队列并被处理。

队列的主要特性包括:

       线性结构:队列中的元素按一定的顺序排列。
       动态变化:队列的大小可以随着元素的入队和出队而动态改变。
       有限或无限容量:取决于实现方式,队列可能有预先设定的最大容量(如固定大小的数组实现),也可以理论上支持无限数量的元素(如链表实现)。
       队列在计算机科学中有多种应用,例如任务调度、消息传递、打印机任务管理、缓冲区管理等场合,都利用了其有序和公平的特性来组织和处理数据流。队列可以用数组或链表等多种数据结构来实现,并且根据应用场景的不同,还发展出了优先队列、循环队列、双端队列等多种变体。

队列接口

  1. package org.alogorithm.queue;
  2. public interface Queue<E> extends Iterable<E> {
  3. /**
  4. * @Description 向队尾插入值
  5. * @Author LY
  6. * @Param [value] 待插入的值
  7. * @return boolean 是否成功
  8. * @Date 2024/1/18 9:53
  9. **/
  10. boolean offer(E value);
  11. /**
  12. * @Description 从队头获取值,并移除
  13. * @Author LY
  14. * @return E 如果队列非空,返回队头值,否则返回null
  15. * @Date 2024/1/18 9:53
  16. **/
  17. E pool();
  18. /**
  19. * @Description 从队头获取值,不移除
  20. * @Author LY
  21. * @return E 如果队列非空,返回队头值,否则返回null
  22. * @Date 2024/1/18 9:55
  23. **/
  24. E peek();
  25. /**
  26. * @Description 检查队列是否为空
  27. * @Author LY
  28. * @return boolean 空返回true,否则返回false
  29. * @Date 2024/1/18 9:55
  30. **/
  31. boolean isEmpty();
  32. /**
  33. * @Description 队列是否满已满
  34. * @Author LY
  35. * @return boolean 满 true 否则 false
  36. * @Date 2024/1/18 11:34
  37. **/
  38. boolean isFull();
  39. }

4.2 链表实现

  1. public class LinkedListQueue<E> implements Queue<E>, Iterable<E> {
  2. public static void main(String[] args) {
  3. LinkedListQueue<Integer>queue=new LinkedListQueue<Integer>(1);
  4. Integer peek1 = queue.peek();
  5. boolean empty1 = queue.isEmpty();
  6. //向尾部添加开始
  7. boolean offer1 = queue.offer(1);
  8. boolean offer2 = queue.offer(2);
  9. //向尾部添加结束
  10. boolean empty2 = queue.isEmpty();
  11. Integer peek2 = queue.peek();
  12. Integer pool1 = queue.pool();
  13. Integer pool2 = queue.pool();
  14. }
  15. @Override
  16. public boolean offer(E value) {
  17. //满了
  18. if(isFull()){
  19. return false;
  20. }
  21. //新节点.next指向头
  22. Node newNode = new Node(value, head);
  23. //原尾节点.next指向新节点
  24. tail.next = newNode;
  25. //tail指向新节点
  26. tail = newNode;
  27. size++;
  28. return true;
  29. }
  30. @Override
  31. public E pool() {
  32. if(this.isEmpty()){
  33. return null;
  34. }
  35. Node<E> first=head.next;
  36. head.next=first.next;
  37. //如果是最后一个节点
  38. if(first==tail){
  39. tail=head;
  40. }
  41. size--;
  42. return first.value;
  43. }
  44. @Override
  45. public E peek() {
  46. if(this.isEmpty()){
  47. return null;
  48. }
  49. return head.next.value;
  50. }
  51. @Override
  52. public boolean isEmpty() {
  53. return tail==head;
  54. }
  55. @Override
  56. public boolean isFull() {
  57. return size==capacity;
  58. }
  59. //节点类
  60. private static class Node<E> {
  61. E value;
  62. Node<E> next;
  63. public Node(E value, Node<E> next) {
  64. this.next = next;
  65. this.value = value;
  66. }
  67. }
  68. @Override
  69. public Iterator iterator() {
  70. return new Iterator<E>() {
  71. Node<E>p=head.next;
  72. @Override
  73. public boolean hasNext() {
  74. return p.next!=head;
  75. }
  76. @Override
  77. public E next() {
  78. E value=p.value;
  79. return value;
  80. }
  81. };
  82. }
  83. Node<E> head = new Node<E>(null, null);
  84. Node<E> tail = head;
  85. //当前大小
  86. private Integer size=0;
  87. //容量
  88. private Integer capacity =Integer.MAX_VALUE;
  89. {
  90. tail.next = head;
  91. }
  92. public LinkedListQueue(Integer capacity) {
  93. this.capacity = capacity;
  94. }
  95. public LinkedListQueue() {
  96. }
  97. }

4.3 环形数组实现

使用环形数组而不是线性数组的原因:

空间利用率:

       在普通线性数组中实现队列时,如果队列的头部和尾部相隔较远(例如,头指针在前而尾指针在后接近数组末尾),中间会有很多未使用的空间。当尾指针到达数组末尾时,若没有足够的空间添加新元素,即使数组前面有空闲位置也无法继续入队,这就出现了所谓的“假溢出”问题。
       环形数组通过计算下标时取模(即循环访问数组)的方式,使得队列的尾部可以“绕回”到数组的头部,这样就可以充分利用整个数组空间,避免了假溢出。
高效性:

       环形队列的所有操作(入队、出队)理论上都可以在常数时间内完成(O(1)复杂度)。这是因为可以通过预先设定好的固定大小的数组,并且维护好头指针和尾指针,直接在对应的位置进行插入和删除操作,无需像线性数组那样可能需要移动大量元素以腾出或填补空间。
适用于实时系统和硬件实现:

       环形队列因其简单高效的特性,在实时操作系统、网络通信、多线程间同步通信等场合被广泛应用。例如在网络设备中,数据包的接收和发送常常利用环形缓冲区(即环形队列的一种形式)来缓存和处理数据流,这样可以确保在高频率的数据交换过程中,不会因为频繁地申请释放内存而导致性能下降或不可预测的行为。

4.3.1 环形数组实现1

需要考虑当前数组满了的情况下头尾指针指向的位置。

  1. package org.alogorithm.queue;
  2. import java.util.Iterator;
  3. import java.util.Spliterator;
  4. import java.util.function.Consumer;
  5. public class ArrayQueue1<E> implements Queue<E>{
  6. public static void main(String[] args) {
  7. ArrayQueue1<Integer>queue=new ArrayQueue1<Integer>(1);
  8. Integer peek1 = queue.peek();
  9. boolean empty1 = queue.isEmpty();
  10. //向尾部添加开始
  11. boolean offer1 = queue.offer(1);
  12. boolean offer2 = queue.offer(2);
  13. //向尾部添加结束
  14. boolean empty2 = queue.isEmpty();
  15. Integer peek2 = queue.peek();
  16. Integer pool1 = queue.pool();
  17. Integer pool2 = queue.pool();
  18. }
  19. private E[] arr;
  20. private int head=0;
  21. private int tail=0;
  22. //抑制警告产生
  23. @SuppressWarnings("all")
  24. public ArrayQueue1(int capacity) {
  25. this.arr = (E[]) new Object[capacity+1];
  26. }
  27. @Override
  28. public boolean offer(E value) {
  29. if(isFull()){
  30. return false;
  31. }
  32. arr[tail]=value;
  33. //防止当前元素时最后一个
  34. tail=(tail+1)% arr.length;
  35. return true;
  36. }
  37. @Override
  38. public E pool() {
  39. if(isEmpty()){
  40. return null;
  41. }
  42. E e = arr[head];
  43. head=(head+1)%arr.length;
  44. return e;
  45. }
  46. @Override
  47. public E peek() {
  48. if(isEmpty()){return null;
  49. }
  50. return arr[head];
  51. }
  52. @Override
  53. public boolean isEmpty() {
  54. return tail==head;
  55. }
  56. @Override
  57. public boolean isFull() {
  58. return (tail+1)%arr.length==head;
  59. }
  60. @Override
  61. public Iterator<E> iterator() {
  62. return new Iterator<E>() {
  63. int p=head;
  64. @Override
  65. public boolean hasNext() {
  66. return p!=tail;
  67. }
  68. @Override
  69. public E next() {
  70. E e = arr[p];
  71. p=(p+1)% arr.length;
  72. return e;
  73. }
  74. };
  75. }
  76. }

4.3.2 环形数组实现2

增加一个size属性,保存全部元素个数,新建数组时大小,判定满和空,添加元素,移除元素做出相应修改。迭代时也应该增加一个count属性。

  1. public class ArrayQueue2<E> implements Queue<E>{
  2. public static void main(String[] args) {
  3. ArrayQueue2<Integer> queue=new ArrayQueue2<Integer>(1);
  4. Integer peek1 = queue.peek();
  5. boolean empty1 = queue.isEmpty();
  6. //向尾部添加开始
  7. boolean offer1 = queue.offer(1);
  8. boolean offer2 = queue.offer(2);
  9. //向尾部添加结束
  10. boolean empty2 = queue.isEmpty();
  11. Integer peek2 = queue.peek();
  12. Integer pool1 = queue.pool();
  13. Integer pool2 = queue.pool();
  14. }
  15. private E[] arr;
  16. private int head=0;
  17. private int tail=0;
  18. //元素个数
  19. private int size=0;
  20. //抑制警告产生
  21. @SuppressWarnings("all")
  22. public ArrayQueue2(int capacity) {
  23. this.arr = (E[]) new Object[capacity];
  24. }
  25. @Override
  26. public boolean offer(E value) {
  27. if(isFull()){
  28. return false;
  29. }
  30. arr[tail]=value;
  31. //防止当前元素时最后一个
  32. tail=(tail+1)% arr.length;
  33. size++;
  34. return true;
  35. }
  36. @Override
  37. public E pool() {
  38. if(isEmpty()){
  39. return null;
  40. }
  41. E e = arr[head];
  42. head=(head+1)%arr.length;
  43. size--;
  44. return e;
  45. }
  46. @Override
  47. public E peek() {
  48. if(isEmpty()){return null;
  49. }
  50. return arr[head];
  51. }
  52. @Override
  53. public boolean isEmpty() {
  54. return size==0;
  55. }
  56. @Override
  57. public boolean isFull() {
  58. return size==arr.length;
  59. }
  60. @Override
  61. public Iterator<E> iterator() {
  62. return new Iterator<E>() {
  63. int p=head;
  64. int count=0;
  65. @Override
  66. public boolean hasNext() {
  67. return count<size;
  68. }
  69. @Override
  70. public E next() {
  71. E e = arr[p];
  72. p=(p+1)% arr.length;
  73. count++;
  74. return e;
  75. }
  76. };
  77. }
  78. }

4.3.3 环形数组实现3

基于方式1,做出优化,head和tail一直递增,使用时在进行计算。

当索引超出int最大值会出现索引为负数的问题。

需要单独处理(int) Integer.toUnsignedLong()。 

方法1
  1. public class ArrayQueue3<E> implements Queue<E>{
  2. public static void main(String[] args) {
  3. ArrayQueue3<Integer> queue=new ArrayQueue3<Integer>(1);
  4. Integer peek1 = queue.peek();
  5. boolean empty1 = queue.isEmpty();
  6. //向尾部添加开始
  7. boolean offer1 = queue.offer(1);
  8. boolean offer2 = queue.offer(2);
  9. //向尾部添加结束
  10. boolean empty2 = queue.isEmpty();
  11. Integer peek2 = queue.peek();
  12. Integer pool1 = queue.pool();
  13. Integer pool2 = queue.pool();
  14. }
  15. private E[] arr;
  16. private int head=0;
  17. private int tail=0;
  18. //抑制警告产生
  19. @SuppressWarnings("all")
  20. public ArrayQueue3(int capacity) {
  21. this.arr = (E[]) new Object[capacity];
  22. }
  23. @Override
  24. public boolean offer(E value) {
  25. if(isFull()){
  26. return false;
  27. }
  28. arr[(int) Integer.toUnsignedLong(tail% arr.length)]=value;
  29. //防止当前元素时最后一个
  30. tail++;
  31. return true;
  32. }
  33. @Override
  34. public E pool() {
  35. if(isEmpty()){
  36. return null;
  37. }
  38. E e = arr[(int) Integer.toUnsignedLong(head% arr.length)];
  39. head++;
  40. return e;
  41. }
  42. @Override
  43. public E peek() {
  44. if(isEmpty()){return null;
  45. }
  46. return arr[(int) Integer.toUnsignedLong(head%arr.length)];
  47. }
  48. @Override
  49. public boolean isEmpty() {
  50. return tail==head;
  51. }
  52. @Override
  53. public boolean isFull() {
  54. return tail-head== arr.length;
  55. }
  56. @Override
  57. public Iterator<E> iterator() {
  58. return new Iterator<E>() {
  59. int p=head;
  60. @Override
  61. public boolean hasNext() {
  62. return p!=tail;
  63. }
  64. @Override
  65. public E next() {
  66. E e = arr[(int) Integer.toUnsignedLong(p% arr.length)];
  67. p++;
  68. return e;
  69. }
  70. };
  71. }
  72. }
方法2

对于求模运算来讲(二进制):

如果除数是2的n次方,那么被除数的后n为即为余数(模)。

求除数后的n位方法:与2^n-1 按位与

      问题:传入数组长度不一定是2^n,可以抛出异常或者转为比入参大最接近的一个2^n次方值,判断一个数是否是2^n可以与该值-1进行按位与,如果结果为0则是2^n,否则则不是。

  1. public class ArrayQueue3_2<E> implements Queue<E>{
  2. public static void main(String[] args) {
  3. ArrayQueue3_2<Integer> queue=new ArrayQueue3_2<Integer>(1);
  4. Integer peek1 = queue.peek();
  5. boolean empty1 = queue.isEmpty();
  6. //向尾部添加开始
  7. boolean offer1 = queue.offer(1);
  8. boolean offer2 = queue.offer(2);
  9. //向尾部添加结束
  10. boolean empty2 = queue.isEmpty();
  11. Integer peek2 = queue.peek();
  12. Integer pool1 = queue.pool();
  13. Integer pool2 = queue.pool();
  14. }
  15. private E[] arr;
  16. private int head=0;
  17. private int tail=0;
  18. //抑制警告产生
  19. @SuppressWarnings("all")
  20. public ArrayQueue3_2(int capacity) {
  21. //方式1
  22. /*if((capacity&capacity-1)!=0){
  23. throw new IllegalArgumentException("长度必须为2的n次方");
  24. }*/
  25. //方法2
  26. /*
  27. * 求以2为底capacity的对数+1
  28. *
  29. * */
  30. /* int res = (int) (Math.log10(capacity-1) / Math.log10(2))+1;
  31. int i = 1 << res;*/
  32. capacity-=1;
  33. capacity|=capacity>>1;
  34. capacity|=capacity>>2;
  35. capacity|=capacity>>4;
  36. capacity|=capacity>>8;
  37. capacity|=capacity>>16;
  38. capacity+=1;
  39. this.arr = (E[]) new Object[capacity];
  40. }
  41. @Override
  42. public boolean offer(E value) {
  43. if(isFull()){
  44. return false;
  45. }
  46. arr[tail& (arr.length-1)]=value;
  47. //防止当前元素时最后一个
  48. tail++;
  49. return true;
  50. }
  51. @Override
  52. public E pool() {
  53. if(isEmpty()){
  54. return null;
  55. }
  56. E e = arr[head&(arr.length-1)];
  57. head++;
  58. return e;
  59. }
  60. @Override
  61. public E peek() {
  62. if(isEmpty()){return null;
  63. }
  64. return arr[head&(arr.length-1)];
  65. }
  66. @Override
  67. public boolean isEmpty() {
  68. return tail==head;
  69. }
  70. @Override
  71. public boolean isFull() {
  72. return tail-head== arr.length;
  73. }
  74. @Override
  75. public Iterator<E> iterator() {
  76. return new Iterator<E>() {
  77. int p=head;
  78. @Override
  79. public boolean hasNext() {
  80. return p!=tail;
  81. }
  82. @Override
  83. public E next() {
  84. E e = arr[p&(arr.length-1)];
  85. p++;
  86. return e;
  87. }
  88. };
  89. }
  90. }

 5.基础数据结构-栈

5.1 相关概念

数据结构栈(Stack)是一种特殊的线性表:
        栈顶(Top): 栈顶是指栈中最靠近“出口”或“操作端”的那个位置。新元素总是被压入(push)到栈顶,当进行弹出(pop)操作时,也是从栈顶移除元素。因此,栈顶始终指向当前栈内的最后一个加入的元素。

        栈底(Bottom): 栈底则是指栈中固定不变的那个位置,通常是在创建栈时初始化的第一个位置,也可以理解为栈中最早加入的那些元素所在的位置。在实际操作中,栈底不发生变化,除非整个栈为空或者重新初始化。

        后进先出(Last In First Out, LIFO):

        最后被压入(push)到栈中的元素将是第一个被弹出(pop)的元素。这意味着在没有其他操作的情况下,栈顶元素总是最后被添加的那一个。
        受限的插入和删除操作:

        栈只允许在栈顶进行插入(称为“压入”或"push"操作)和删除(称为“弹出”或"pop"操作)。不能直接访问或修改栈内的中间元素。

5.2 接口

  1. public interface Stock<E> extends Iterable<E> {
  2. /**
  3. * @Description 向栈压入元素
  4. * @Author LY
  5. * @Param [value] 待压入的值
  6. * @return boolean 是否成功
  7. * @Date 2024/1/18 9:53
  8. **/
  9. boolean push(E value);
  10. /**
  11. * @Description 从栈顶弹出元素
  12. * @Author LY
  13. * @return E 如果栈非空,返回栈顶元素,否则返回null
  14. * @Date 2024/1/18 9:53
  15. **/
  16. E pop();
  17. /**
  18. * @Description 返回栈顶元素,不弹出
  19. * @Author LY
  20. * @return E 如果栈非空,返回栈顶元素,否则返回null
  21. * @Date 2024/1/18 9:55
  22. **/
  23. E peek();
  24. /**
  25. * @Description 检查栈是否为空
  26. * @Author LY
  27. * @return boolean 空返回true,否则返回false
  28. * @Date 2024/1/18 9:55
  29. **/
  30. boolean isEmpty();
  31. /**
  32. * @Description 栈是否满已满
  33. * @Author LY
  34. * @return boolean 满 true 否则 false
  35. * @Date 2024/1/18 11:34
  36. **/
  37. boolean isFull();
  38. }

5.3 链表实现

  1. public class LinkedListStock<E> implements Stock<E>{
  2. public static void main(String[] args) {
  3. LinkedListStock<Integer>stock=new LinkedListStock<>(2);
  4. boolean empty1 = stock.isEmpty();
  5. boolean full1 = stock.isFull();
  6. boolean push1 = stock.push(1);
  7. boolean push2 = stock.push(2);
  8. boolean push3 = stock.push(3);
  9. boolean empty2 = stock.isEmpty();
  10. boolean full2 = stock.isFull();
  11. Integer peek1 = stock.peek();
  12. Integer pop1 = stock.pop();
  13. Integer pop2 = stock.pop();
  14. Integer pop3 = stock.pop();
  15. Integer peek2 = stock.peek();
  16. }
  17. //容量
  18. private int capatity=Integer.MAX_VALUE;
  19. //元素个数
  20. private int size=0;
  21. private Node head=new Node(null,null);
  22. public LinkedListStock() {
  23. }
  24. public LinkedListStock(int capatity) {
  25. this.capatity = capatity;
  26. }
  27. static class Node<E>{
  28. E value;
  29. Node<E> next;
  30. public Node(E value, Node<E> next) {
  31. this.value = value;
  32. this.next = next;
  33. }
  34. }
  35. @Override
  36. public boolean push(E value) {
  37. if(isFull()){
  38. return false;
  39. }
  40. Node node = new Node(value, head.next);
  41. head.next=node;
  42. size++;
  43. return true;
  44. }
  45. @Override
  46. public E pop() {
  47. if(isEmpty()){
  48. return null;
  49. }
  50. Node<E> first = head.next;
  51. head.next=first.next;
  52. size--;
  53. return first.value;
  54. }
  55. @Override
  56. public E peek() {
  57. if(isEmpty()){
  58. return null;
  59. }
  60. Node<E> first = head.next;
  61. return first.value;
  62. }
  63. @Override
  64. public boolean isEmpty() {
  65. return size==0;
  66. }
  67. @Override
  68. public boolean isFull() {
  69. return size==capatity;
  70. }
  71. @Override
  72. public Iterator<E> iterator() {
  73. return new Iterator<E>() {
  74. Node<E> p=head;
  75. @Override
  76. public boolean hasNext() {
  77. return p!=null;
  78. }
  79. @Override
  80. public E next() {
  81. E value = p.value;
  82. p=p.next;
  83. return value;
  84. }
  85. };
  86. }
  87. }

5.4 数组实现

  1. public class ArrayStock<E> implements Stock<E>{
  2. public static void main(String[] args) {
  3. ArrayStock<Integer> stock=new ArrayStock<>(2);
  4. boolean empty1 = stock.isEmpty();
  5. boolean full1 = stock.isFull();
  6. boolean push1 = stock.push(1);
  7. boolean push2 = stock.push(2);
  8. boolean push3 = stock.push(3);
  9. boolean empty2 = stock.isEmpty();
  10. boolean full2 = stock.isFull();
  11. Integer peek1 = stock.peek();
  12. Integer pop1 = stock.pop();
  13. Integer pop2 = stock.pop();
  14. Integer pop3 = stock.pop();
  15. Integer peek2 = stock.peek();
  16. }
  17. private E[]arr;
  18. private int top;
  19. //容量
  20. private int capatity=Integer.MAX_VALUE;
  21. public ArrayStock() {
  22. }
  23. @SuppressWarnings("all")
  24. public ArrayStock(int capatity) {
  25. this.arr = (E[]) new Object[capatity];
  26. this.capatity=capatity;
  27. }
  28. @Override
  29. public boolean push(E value) {
  30. if(isFull()){
  31. return false;
  32. }
  33. /* arr[top]=value;
  34. top++;*/
  35. arr[top++]=value;
  36. return true;
  37. }
  38. @Override
  39. public E pop() {
  40. if(isEmpty()){
  41. return null;
  42. }
  43. E e = arr[--top];
  44. return e;
  45. }
  46. @Override
  47. public E peek() {
  48. if(isEmpty()){
  49. return null;
  50. }
  51. return arr[top-1];
  52. }
  53. @Override
  54. public boolean isEmpty() {
  55. return top==0;
  56. }
  57. @Override
  58. public boolean isFull() {
  59. return top==capatity;
  60. }
  61. @Override
  62. public Iterator<E> iterator() {
  63. return new Iterator<E>() {
  64. int p=top;
  65. @Override
  66. public boolean hasNext() {
  67. return p>0;
  68. }
  69. @Override
  70. public E next() {
  71. return arr[--p];
  72. }
  73. };
  74. }
  75. }

 6.其他队列

6.1 对比

        双端队列(Double-Ended Queue, deque)、栈(Stack)和队列(Queue)是三种基本且重要的数据结构,它们各自具有不同的操作特性和使用场景:

栈 (Stack):

        结构特点:栈是一种后进先出(Last-In-First-Out, LIFO)的数据结构,它只允许在一端进行插入和删除操作。这一端通常称为栈顶。
        操作特性:主要支持push(入栈,将元素添加到栈顶)、pop(出栈,移除并返回栈顶元素)以及peek(查看栈顶元素但不移除)等操作。
        应用场景:栈常用于实现函数调用堆栈、括号匹配检查、深度优先搜索算法(DFS)等。

队列 (Queue):

        结构特点:队列遵循先进先出(First-In-First-Out, FIFO)的原则,允许在队尾插入元素(enqueue或add),而在队头删除元素(dequeue或remove)。
        操作特性:主要支持enqueue(入队)、dequeue(出队)、peek(查看队头元素但不移除)以及判断是否为空等操作。
        应用场景:队列常见于多线程同步、任务调度、广度优先搜索算法(BFS)、消息传递系统等需要有序处理多个任务的场合。

6.2 双端队列

6.2.1 概念

双端队列 (Double-Ended Queue, deque):

        结构特点:可以在两端进行插入和删除的序列容器,同时具备队列和栈的部分特性。
        操作特性:包括push_front/pop_front(在/从队头操作)、push_back/pop_back(在/从队尾操作)等功能。
        应用场景:滑动窗口算法、回文串检测、实时事件处理等。

6.2.2 链表实现

  1. public class LinkedListDeque<E> implements Deque<E> {
  2. public static void main(String[] args) {
  3. LinkedListDeque<Integer>linkedListDeque=new LinkedListDeque<>(5);
  4. boolean offerLast1 = linkedListDeque.offerLast(1);
  5. boolean offerLast2 = linkedListDeque.offerLast(2);
  6. boolean offerLast3 = linkedListDeque.offerLast(3);
  7. boolean offerLast4 = linkedListDeque.offerLast(4);
  8. boolean offerLast5 = linkedListDeque.offerLast(5);
  9. boolean offerLast6 = linkedListDeque.offerLast(6);
  10. Integer first1 = linkedListDeque.poolFirst();
  11. Integer first2 = linkedListDeque.poolFirst();
  12. Integer last1 = linkedListDeque.poolLast();
  13. Integer last2 = linkedListDeque.poolLast();
  14. Integer last3 = linkedListDeque.poolLast();
  15. Integer last4 = linkedListDeque.poolLast();
  16. }
  17. private int capacity;
  18. private int size;
  19. Node<E> sentinel=new Node<E>(null,null,null);
  20. public LinkedListDeque(int capacity) {
  21. this.capacity = capacity;
  22. sentinel.next=sentinel;
  23. sentinel.prev=sentinel;
  24. }
  25. static class Node<E>{
  26. Node prev;
  27. E value;
  28. Node next;
  29. public Node(Node<E> prev, E value, Node<E> next) {
  30. this.prev = prev;
  31. this.value = value;
  32. this.next = next;
  33. }
  34. }
  35. @Override
  36. public boolean offerFirst(E e) {
  37. if(isFull()){
  38. return false;
  39. }
  40. //上一个节点是哨兵,下一个节点是哨兵.next
  41. Node oldFirst = sentinel.next;
  42. //新的节点
  43. Node<E> addNode=new Node<E>(sentinel,e,oldFirst);
  44. //旧节点修改prev指针
  45. oldFirst.prev=addNode;
  46. //修改哨兵next指针
  47. sentinel.next=addNode;
  48. //增加容量
  49. size++;
  50. return true;
  51. }
  52. @Override
  53. public boolean offerLast(E e) {
  54. if(isFull()){
  55. return false;
  56. }
  57. //旧的最后一个节点
  58. Node oldLast = sentinel.prev;
  59. //新的节点
  60. Node addNode=new Node(oldLast,e,sentinel);
  61. //旧节点修改next指针
  62. oldLast.next=addNode;
  63. //修改哨兵prev指针
  64. sentinel.prev=addNode;
  65. size++;
  66. return true;
  67. }
  68. @Override
  69. public E poolFirst() {
  70. if(isEmpty()){
  71. return null;
  72. }
  73. //需要出队列的节点
  74. Node<E> poolNode=sentinel.next;
  75. //移除节点的下一个节点
  76. Node<E>nextNode=poolNode.next;
  77. //修改下一个节点.prev指针
  78. nextNode.prev=sentinel;
  79. //修改哨兵.next指针
  80. sentinel.next=nextNode;
  81. size--;
  82. return poolNode.value;
  83. }
  84. @Override
  85. public E poolLast() {
  86. if(isEmpty()){
  87. return null;
  88. }
  89. //需要出队列的节点
  90. Node<E> poolNode=sentinel.prev;
  91. //移除节点的上一个节点
  92. Node<E>prevNode=poolNode.prev;
  93. //修改上一个节点.next指针
  94. prevNode.next=sentinel;
  95. //修改哨兵.prev指针
  96. sentinel.prev=prevNode;
  97. size--;
  98. return poolNode.value;
  99. }
  100. @Override
  101. public E peekFirst() {
  102. if(isEmpty()){
  103. return null;
  104. }
  105. return (E) sentinel.next.value;
  106. }
  107. @Override
  108. public E peekLast() {
  109. if(isEmpty()){
  110. return null;
  111. }
  112. return (E) sentinel.prev.value;
  113. }
  114. @Override
  115. public boolean isEmpty() {
  116. return size==0;
  117. }
  118. @Override
  119. public boolean isFull() {
  120. return size==capacity;
  121. }
  122. @Override
  123. public Iterator<E> iterator() {
  124. return new Iterator<E>() {
  125. Node<E> piont=sentinel.next;
  126. @Override
  127. public boolean hasNext() {
  128. return piont!=sentinel;
  129. }
  130. @Override
  131. public E next() {
  132. E val= piont.value;
  133. piont=piont.next;
  134. return val;
  135. }
  136. };
  137. }
  138. }

6.2.3 数组实现

  1. public class ArrayDeque1<E> implements Deque<E>{
  2. public static void main(String[] args) {
  3. ArrayDeque1<Integer> arrayDeque1=new ArrayDeque1(3);
  4. boolean full1 = arrayDeque1.isFull();
  5. boolean empty1 = arrayDeque1.isEmpty();
  6. boolean offerFirst1 = arrayDeque1.offerFirst(1);
  7. boolean offerFirst2 = arrayDeque1.offerFirst(2);
  8. boolean offerFirst3 = arrayDeque1.offerLast(3);
  9. boolean offerFirst4 = arrayDeque1.offerLast(4);
  10. boolean full2 = arrayDeque1.isFull();
  11. boolean empty2 = arrayDeque1.isEmpty();
  12. int poolFirst1= arrayDeque1.poolFirst();
  13. int poolLast1= arrayDeque1.poolLast();
  14. }
  15. E[]array;
  16. private int head;
  17. private int tail;
  18. /*
  19. * tail不存值,实际长度应该用参数+1
  20. * */
  21. public ArrayDeque1(int capacity) {
  22. array= (E[]) new Object [capacity+1];
  23. }
  24. @Override
  25. /*
  26. * 先head-1再添加元素
  27. * */
  28. public boolean offerFirst(E e) {
  29. if(isFull()){
  30. return false;
  31. }
  32. head= dec(head, array.length);
  33. array[head]=e;
  34. return true;
  35. }
  36. @Override
  37. /*
  38. * 添加元素后,tail+1
  39. * */
  40. public boolean offerLast(E e) {
  41. if(isFull()){
  42. return false;
  43. }
  44. array[tail]=e;
  45. tail= inc(tail, array.length);
  46. return true;
  47. }
  48. @Override
  49. /*
  50. * 先获取值,再head++(转换为合法索引)
  51. * */
  52. public E poolFirst() {
  53. if(isEmpty()){
  54. return null;
  55. }
  56. E e = array[head];
  57. //取消引用,自动释放内存
  58. array[head]=null;
  59. head=inc(head,array.length);
  60. return e;
  61. }
  62. @Override
  63. /*
  64. * 先tail-- ,再获取元素(转换为合法索引)
  65. * */
  66. public E poolLast() {
  67. if(isEmpty()){
  68. return null;
  69. }
  70. tail=dec(tail,array.length);
  71. E e = array[tail];
  72. //取消引用,自动释放内存
  73. array[tail]=null;
  74. return e;
  75. }
  76. @Override
  77. public E peekFirst() {
  78. if(isEmpty()){
  79. return null;
  80. }
  81. return array[head];
  82. }
  83. /*
  84. * 获取 tail-1位置的元素
  85. * */
  86. @Override
  87. public E peekLast() {
  88. return array[dec(tail-1,array.length)];
  89. }
  90. @Override
  91. /*
  92. * 头尾指向同一个位置即为空
  93. * */
  94. public boolean isEmpty() {
  95. return head==tail;
  96. }
  97. @Override
  98. /*
  99. * head ~ tail =数组.length-1
  100. * tail>head tail-head ==数组.length-1
  101. * tail<head head-tail==1
  102. * */
  103. public boolean isFull() {
  104. if(head <tail){
  105. return tail-head==array.length-1;
  106. }else if(head >tail){
  107. return head-tail==1;
  108. }
  109. return false;
  110. }
  111. @Override
  112. public Iterator<E> iterator() {
  113. return new Iterator<E>() {
  114. int poin=head;
  115. @Override
  116. public boolean hasNext() {
  117. return poin!=tail;
  118. }
  119. @Override
  120. public E next() {
  121. E e = array[poin];
  122. poin = inc(poin + 1, array.length);
  123. return e;
  124. }
  125. };
  126. }
  127. /*
  128. * 索引++之后越界恢复成0
  129. * */
  130. static int inc(int i, int length){
  131. if(++i>=length){
  132. return 0;
  133. }
  134. return i;
  135. }
  136. /*
  137. * 索引--之后越界恢复成数组长度
  138. * */
  139. static int dec(int i, int length){
  140. if(--i <0)return length-1;
  141. return i;
  142. }
  143. }

注意:基本类型占用字节相同,不需要考虑内存释放,但是引用数据类型要考虑内存释放问题(当不删除元素时,该索引位置应该置位null,否则垃圾回收器不会自动回收)。

6.3 优先级队列

6.3.1 概念

优先级队列 (Priority Queue):

        结构特点:每个元素都有一个优先级,每次取出的是当前优先级最高的元素。可以基于堆实现。
        操作特性:主要包括insert(插入元素)、delete_min/max(移除并返回优先级最高/最低的元素)等。
        应用场景:Dijkstra算法中的最短路径搜索、操作系统中的进程调度、事件驱动编程中的事件处理等。

6.3.2 无序数组实现

基于无序数组的优先级队列(例如使用索引堆):

插入元素:

        无序数组实现如索引堆等结构可以相对快速地插入元素,并通过索引维护堆属性,插入操作的时间复杂度一般为O(log n)。
删除最高优先级元素:

        删除最小元素通常涉及到重新调整堆结构以满足堆属性,即保证父节点的优先级高于或等于子节点,时间复杂度同样是O(log n)。
优势:

        插入和删除操作的时间复杂度都相对较低,都是O(log n),适用于动态变化的数据集合。
相对于有序数组,插入和删除操作更加高效,特别是在大量元素插入、删除的情况下。
劣势:

        查找最高优先级元素并不像有序数组那样简单,每次取出最小元素都需要调整堆结构。

  1. //基于无序数组的实现
  2. public class PriorityQueue<E extends Priority> implements Queue<E> {
  3. public static void main(String[] args) {
  4. Test test1 = new Test(1, "任务9");
  5. Test test2 = new Test(2, "任务8");
  6. Test test3 = new Test(3, "任务7");
  7. Test test4 = new Test(4, "任务6");
  8. PriorityQueue priorityQueue=new PriorityQueue(3);
  9. boolean full1 = priorityQueue.isFull();
  10. boolean empty1 = priorityQueue.isEmpty();
  11. Priority peek1 = priorityQueue.peek();
  12. boolean offer1 = priorityQueue.offer(test1);
  13. boolean offer2 = priorityQueue.offer(test2);
  14. boolean offer3 = priorityQueue.offer(test3);
  15. boolean offer4 = priorityQueue.offer(test4);
  16. boolean full2 = priorityQueue.isFull();
  17. boolean empty2 = priorityQueue.isEmpty();
  18. Priority peek2 = priorityQueue.peek();
  19. Priority pool1 = priorityQueue.pool();
  20. Priority pool2 = priorityQueue.pool();
  21. Priority pool3 = priorityQueue.pool();
  22. Priority pool4 = priorityQueue.pool();
  23. }
  24. static class Test extends Priority {
  25. String task;
  26. public Test(int priority, String task) {
  27. super(priority);
  28. this.task = task;
  29. }
  30. }
  31. @Getter
  32. static Priority[] array;
  33. private static int size=0;
  34. public PriorityQueue(int capacity) {
  35. array = new Priority[capacity];
  36. }
  37. @Override
  38. public boolean offer(E value) {
  39. if (isFull()) {
  40. return false;
  41. }
  42. array[size] = value;
  43. size++;
  44. return true;
  45. }
  46. @Override
  47. public E pool() {
  48. if(isEmpty()){
  49. return null;
  50. }
  51. int maxIndex = getMaxIndex();
  52. Priority priority = array[maxIndex];
  53. remove(maxIndex);
  54. return (E) priority;
  55. }
  56. //移除元素
  57. private void remove(int maxIndex) {
  58. if(maxIndex<size-1){
  59. //不是最后一个元素
  60. System.arraycopy(array,maxIndex+1,array,maxIndex,size-1-maxIndex);
  61. }
  62. size--;
  63. }
  64. private static int getMaxIndex(){
  65. int max = 0;
  66. for (int i = 0; i < array.length; i++) {
  67. if (array[max].priority < array[i].priority) {
  68. max = i;
  69. }
  70. }
  71. return max;
  72. }
  73. @Override
  74. public E peek() {
  75. if(isEmpty()){
  76. return null;
  77. }
  78. int max = 0;
  79. for (int i = 0; i < size; i++) {
  80. if (array[max].priority < array[i].priority) {
  81. max = i;
  82. }
  83. }
  84. Priority priority = array[max];
  85. return (E) priority;
  86. }
  87. @Override
  88. public boolean isEmpty() {
  89. return size == 0;
  90. }
  91. @Override
  92. public boolean isFull() {
  93. return size == array.length;
  94. }
  95. @Override
  96. public Iterator<E> iterator() {
  97. return new Iterator<E>() {
  98. private int p;
  99. @Override
  100. public boolean hasNext() {
  101. return p < array.length;
  102. }
  103. @Override
  104. public E next() {
  105. Priority priority = array[p];
  106. p++;
  107. return (E) priority;
  108. }
  109. };
  110. }
  111. }

6.3.3 有序数组实现

基于有序数组的优先级队列:

插入元素:

        插入新元素需要保持数组的有序性,因此在插入过程中可能需要移动部分或全部已存在的元素以腾出位置给新元素,时间复杂度通常是O(n)。
由于数组本身是有序的,可以通过二分查找快速定位到插入点,但是插入后的调整仍然涉及元素移动。
        删除最高优先级元素:

可以直接访问并删除数组的第一个元素(假设是最小元素),时间复杂度为O(1)。
删除后如果需要维持有序,可能需要将最后一个元素移动到被删除元素的位置,或者使用某种方法来“填补”空缺,总体上删除操作的时间复杂度也是O(n)。
优势:

        查找最高优先级元素的时间复杂度低,为O(1)。
如果插入不是非常频繁且数组大小相对稳定,那么其效率可能会较高,因为查询和删除最小元素高效。
劣势:

        插入和删除元素的成本高,尤其是当数组较大时,频繁的移动操作会显著降低性能。

  1. //基于有序数组的实现
  2. public class PriorityQueue3<E extends Priority> implements Queue<E> {
  3. public static void main(String[] args) {
  4. Test test1 = new Test(1, "任务9");
  5. Test test2 = new Test(2, "任务8");
  6. Test test3 = new Test(3, "任务7");
  7. Test test4 = new Test(4, "任务6");
  8. PriorityQueue3 priorityQueue=new PriorityQueue3(3);
  9. boolean full1 = priorityQueue.isFull();
  10. boolean empty1 = priorityQueue.isEmpty();
  11. Priority peek1 = priorityQueue.peek();
  12. boolean offer2 = priorityQueue.offer(test2);
  13. boolean offer1 = priorityQueue.offer(test1);
  14. boolean offer3 = priorityQueue.offer(test3);
  15. boolean offer4 = priorityQueue.offer(test4);
  16. boolean full2 = priorityQueue.isFull();
  17. boolean empty2 = priorityQueue.isEmpty();
  18. Priority peek2 = priorityQueue.peek();
  19. Priority pool1 = priorityQueue.pool();
  20. Priority pool2 = priorityQueue.pool();
  21. Priority pool3 = priorityQueue.pool();
  22. Priority pool4 = priorityQueue.pool();
  23. }
  24. static class Test extends Priority {
  25. String task;
  26. public Test(int priority, String task) {
  27. super(priority);
  28. this.task = task;
  29. }
  30. }
  31. @Getter
  32. static Priority[] array;
  33. private static int size;
  34. public PriorityQueue3(int capacity) {
  35. array = new Priority[capacity];
  36. }
  37. @Override
  38. public boolean offer(E value) {
  39. if (isFull()) {
  40. return false;
  41. }
  42. insert( value);
  43. size++;
  44. return true;
  45. }
  46. private void insert(E value) {
  47. int i=size-1;
  48. while (i>=0 && array[i].priority> value.priority){
  49. //优先级大于入参向上移动
  50. array[i+1]=array[i];
  51. i--;
  52. }
  53. //在比他小的索引后面插入元素
  54. array[i+1]=value;
  55. }
  56. @Override
  57. public E pool() {
  58. if(isEmpty()){
  59. return null;
  60. }
  61. E priority = (E) array[size - 1];
  62. array[--size]=null;
  63. return (priority) ;
  64. }
  65. @Override
  66. public E peek() {
  67. if(isEmpty()){
  68. return null;
  69. }
  70. return (E) array[size-1];
  71. }
  72. @Override
  73. public boolean isEmpty() {
  74. return size == 0;
  75. }
  76. @Override
  77. public boolean isFull() {
  78. return size == array.length;
  79. }
  80. @Override
  81. public Iterator<E> iterator() {
  82. return new Iterator<E>() {
  83. private int p;
  84. @Override
  85. public boolean hasNext() {
  86. return p < array.length;
  87. }
  88. @Override
  89. public E next() {
  90. Priority priority = array[p];
  91. p++;
  92. return (E) priority;
  93. }
  94. };
  95. }
  96. }

6.3.4 基于堆实现

6.3.4.1 堆的概念

计算机科学中,堆是一种基于树的数据结构,通常用完全二叉树来实现。堆的特性如下:

完全二叉树属性:

        堆是一个完全二叉树,这意味着除了最后一层之外,其他每一层都被完全填满,并且所有节点都尽可能地集中在左侧。
堆序性质:

        在大顶堆(也称为最大堆)中,对于任意节点 C 与其父节点 P,满足不等式 P.value >= C.value,即每个父节点的值都大于或等于其子节点的值。
        在小顶堆(也称为最小堆)中,对于任意节点 C 与其父节点 P,满足不等式 P.value <= C.value,即每个父节点的值都小于或等于其子节点的值。
操作特性:

        插入操作:在保持堆序性质的前提下插入新元素,可能需要调整堆中的元素位置。
        删除操作:删除堆顶元素(即最大或最小元素),也需要重新调整堆结构以保证剩余元素仍然满足堆序性质。
        查找最大/最小元素:堆顶元素就是整个堆中的最大(在大顶堆中)或最小(在小顶堆中)元素,无需遍历整个堆即可直接获取。
存储方式:

        堆可以用数组来高效存储,由于是完全二叉树,可以利用数组下标与节点层级、左右子节点之间的关系紧密关联的特点,节省存储空间并加快访问速度。
应用:

        堆常用于实现优先队列,能够快速找到并移除具有最高或最低优先级的元素。
        在许多算法和数据处理中,如求解最值问题、堆排序算法以及图的最小生成树算法(例如Prim算法或Kruskal算法结合使用优先队列)中都有重要应用。

6.3.4.2 堆的分类

堆在计算机科学中主要根据其内部元素的排序特性进行分类,可以分为以下两种类型:

        大顶堆(Max Heap): 在大顶堆中,父节点的值总是大于或等于其所有子节点的值。堆的根节点是整个堆中的最大元素,因此,大顶堆常被用于实现优先队列,其中队列头部始终是当前最大的元素。

        小顶堆(Min Heap): 在小顶堆中,父节点的值总是小于或等于其所有子节点的值。与大顶堆相反,小顶堆的根节点是整个堆中的最小元素,同样适用于实现优先队列,只不过在这种情况下,队列头部提供的是当前最小的元素。

        这两种类型的堆都是完全二叉树结构,并且通常通过数组来实现存储,利用数组索引与树节点之间的逻辑关系快速访问和操作堆中的元素。除了大顶堆和小顶堆之外,还有其他形式的堆,例如斐波那契堆(Fibonacci Heap),它是一种更为复杂的高效数据结构,提供了更优化的插入、删除和合并操作,但并不像普通二叉堆那样要求严格的父节点与子节点的大小关系。

6.3.4.3 堆的计算

        在树型数据结构中,从索引0开始存储节点数据是常见的做法,尤其是在数组或链表实现的树结构里。这里我们区分两种情况:

已知子节点求父节点:

        如果树结构使用数组来表示,并且我们知道子节点对应的数组索引,那么根据某种固定规则(如:每个节点的左孩子通常位于2倍索引处,右孩子位于2倍索引 + 1处),可以计算出父节点的索引。
        在完全二叉树中,给定一个节点i的索引,其父节点的索引可以通过 (i - 1) / 2 计算得出(向下取整)。
已知父节点求子节点:

        同样地,如果知道父节点在数组中的索引,我们可以很容易地找到它的两个子节点。
        左子节点的索引通常是 2 * 父节点索引 + 1。
        右子节点的索引通常是 2 * 父节点索引 + 2。

如果从索引1开始存储节点:

        已知子节点求父节点为: (i ) / 2。

        已知父节点求子节点为:2i,2i+1。
        请注意,这些规则适用于采用数组实现的完全二叉树和几乎完全二叉树等特定场景下的节点关系查找。对于其他类型的树或者非完全二叉树,可能需要额外的数据结构或不同的逻辑来维护父子节点之间的关系。例如,在链表形式的树结构中,父节点会直接持有指向其子节点的指针,因此不需要通过计算索引来定位子节点。

6.3.4.4 基于大顶堆实现
  1. //基于有序数组的实现
  2. public class PriorityQueue4<E extends Priority> implements Queue<E> {
  3. public static void main(String[] args) {
  4. Test test1 = new Test(1, "任务9");
  5. Test test2 = new Test(2, "任务8");
  6. Test test3 = new Test(3, "任务7");
  7. Test test4 = new Test(4, "任务6");
  8. PriorityQueue4 priorityQueue = new PriorityQueue4(3);
  9. boolean full1 = priorityQueue.isFull();
  10. boolean empty1 = priorityQueue.isEmpty();
  11. Priority peek1 = priorityQueue.peek();
  12. boolean offer2 = priorityQueue.offer(test2);
  13. boolean offer1 = priorityQueue.offer(test1);
  14. boolean offer3 = priorityQueue.offer(test3);
  15. boolean offer4 = priorityQueue.offer(test4);
  16. boolean full2 = priorityQueue.isFull();
  17. boolean empty2 = priorityQueue.isEmpty();
  18. Priority peek2 = priorityQueue.peek();
  19. Priority pool1 = priorityQueue.pool();
  20. Priority pool2 = priorityQueue.pool();
  21. Priority pool3 = priorityQueue.pool();
  22. Priority pool4 = priorityQueue.pool();
  23. }
  24. static class Test extends Priority {
  25. String task;
  26. public Test(int priority, String task) {
  27. super(priority);
  28. this.task = task;
  29. }
  30. }
  31. @Getter
  32. static Priority[] array;
  33. private static int size;
  34. public PriorityQueue4(int capacity) {
  35. array = new Priority[capacity];
  36. }
  37. /*
  38. * 1.入队新元素,加入到数组末尾(索引child)
  39. * 2.不断比较新元素与父节点的优先级。
  40. * 如果优先级低于新节点,则向下移动,并寻找下一个paraent
  41. * 直至父元素优先级跟高或者child==0为止
  42. * */
  43. @Override
  44. public boolean offer(E value) {
  45. if (isFull()) {
  46. return false;
  47. }
  48. if(isEmpty()){
  49. array[0]=value;
  50. }
  51. int child = size++;
  52. int parent = (child - 1) / 2;
  53. //新元素和父元素优先级对比
  54. while (value.priority > array[parent].priority && child != 0) {
  55. array[child] = array[parent];
  56. //子节点指向父节点,父节点指向,原本的父节点的父节点
  57. child = parent;
  58. parent = (child - 1) / 2;
  59. }
  60. array[child] = value;
  61. return true;
  62. }
  63. /*
  64. * 1.由于移除最后一个元素效率比较高,
  65. * 故应将第一个优先级最高的元素与最后一个元素互换。
  66. * 2.将堆顶元素与两个子元素比较,与较大的那个更换,
  67. * 直至该节点为最后一个节点或者子节点都小于该节点
  68. *
  69. * */
  70. @Override
  71. public E pool() {
  72. if (isEmpty()) return null;
  73. swap(0, size - 1);
  74. size--;
  75. //保存优先级最大的元素
  76. Priority p = array[size];
  77. //置空垃圾回收
  78. array[size] = null;
  79. //堆顶下潜
  80. down(0);
  81. return (E) p;
  82. }
  83. private void swap(int i, int j) {
  84. Priority t = array[i];
  85. array[i] = array[j];
  86. array[j] = t;
  87. }
  88. private void down(int parent) {
  89. int left = parent * 2 + 1;
  90. int right = left + 1;
  91. int bigChild = parent;
  92. //比较左侧元素与父元素
  93. if (left < size && array[left].priority > array[bigChild].priority) bigChild = left;
  94. //比较右侧元素与父元素
  95. if (right < size && array[right].priority > array[bigChild].priority) bigChild = right;
  96. //交换较大的元素
  97. if (bigChild != parent) {
  98. swap(bigChild, parent);
  99. //以最大的子元素节点索引为参数继续执行下潜操作
  100. down(bigChild);
  101. }
  102. }
  103. @Override
  104. public E peek() {
  105. if(isEmpty())return null;
  106. return (E) array[0];
  107. }
  108. @Override
  109. public boolean isEmpty() {
  110. return size == 0;
  111. }
  112. @Override
  113. public boolean isFull() {
  114. return size == array.length;
  115. }
  116. @Override
  117. public Iterator<E> iterator() {
  118. return new Iterator<E>() {
  119. private int p;
  120. @Override
  121. public boolean hasNext() {
  122. return p < array.length;
  123. }
  124. @Override
  125. public E next() {
  126. Priority priority = array[p];
  127. p++;
  128. return (E) priority;
  129. }
  130. };
  131. }
  132. }

6.4 阻塞队列

  1. /*
  2. * 为了避免多线程导致的数据混乱,例如:线程T1 修改之后未执行tail++,T2执行赋值,
  3. * 会把T1赋值给覆盖掉,然后执行两次tail++,最后导致数据混乱。
  4. * 1.synchronized 关键字,简单功能少
  5. * 2.ReentrantLock 可重入锁,功能多
  6. * */
  7. public class TestThreadUnsafe {
  8. public static void main(String[] args) {
  9. TestThreadUnsafe queue = new TestThreadUnsafe();
  10. /* queue.offer("E1");
  11. queue.offer("E2");*/
  12. new Thread(() -> {
  13. try {
  14. queue.offer("E1");
  15. } catch (InterruptedException e) {
  16. throw new RuntimeException(e);
  17. }
  18. }, "t1").start();
  19. new Thread(() -> {
  20. try {
  21. queue.offer("E2");
  22. } catch (InterruptedException e) {
  23. throw new RuntimeException(e);
  24. }
  25. }, "t2").start();
  26. }
  27. private final String[] array = new String[10];
  28. private int tail = 0;
  29. private int size = 0;
  30. ReentrantLock reentrantLock = new ReentrantLock();
  31. Condition tailWaits=reentrantLock.newCondition();//条件对象集合
  32. public void offer(String s) throws InterruptedException {
  33. //加锁 等待直到解锁
  34. // reentrantLock.lock();
  35. // 加锁,阻塞过程中随时打断抛出异常
  36. reentrantLock.lockInterruptibly();
  37. try {
  38. /*
  39. * 如果使用if 多线程情况下,会导致新加入的线程未走判断,等待的线程被唤醒,两个线程同时向下执行
  40. * 这种唤醒叫做虚假唤醒,每次都应该循环判断是否满了,而不应该用if
  41. * */
  42. while (isFull()){
  43. //等待 让线程进入阻塞状态
  44. tailWaits.await();
  45. // 阻塞后唤醒线程使用,且必须配合锁使用
  46. /* reentrantLock.lockInterruptibly();
  47. tailWaits.signal();
  48. reentrantLock.unlock();*/
  49. }
  50. array[tail] = s;
  51. if(++tail== array.length){
  52. tail=0;
  53. }
  54. size++;
  55. } finally {
  56. //解锁必须执行
  57. reentrantLock.unlock();
  58. }
  59. }
  60. public boolean isFull(){
  61. return size==array.length;
  62. }
  63. public String toString() {
  64. return Arrays.toString(array);
  65. }
  66. }

6.4.1 单锁实现

  1. /*
  2. * 用锁保证线程安全。
  3. * 条件变量让pool或者offer线程进入等待,而不是循环尝试,占用cpu
  4. * */
  5. public class BlockingQueue1<E> implements BlockingQueue<E> {
  6. public static void main(String[] args) {
  7. BlockingQueue1<String> blockingQueue1=new BlockingQueue1<>(3);
  8. try {
  9. blockingQueue1.offer("任务1");
  10. blockingQueue1.offer("任务2");
  11. blockingQueue1.offer("任务3");
  12. boolean offer = blockingQueue1.offer("任务4", 2000);
  13. System.out.println(offer);
  14. } catch (InterruptedException e) {
  15. throw new RuntimeException(e);
  16. }
  17. }
  18. private final E[] array;
  19. private int head;
  20. private int tail;
  21. private int size;
  22. private ReentrantLock lock = new ReentrantLock();
  23. private Condition headWaits = lock.newCondition();
  24. private Condition tailWaits = lock.newCondition();
  25. public BlockingQueue1(int capacity) {
  26. this.array = (E[]) new Object[capacity];
  27. }
  28. @Override
  29. public void offer(E e) throws InterruptedException {
  30. lock.lockInterruptibly();
  31. try {
  32. //防止虚假唤醒
  33. while (isFull()) {
  34. tailWaits.await();
  35. }
  36. array[tail] = e;
  37. if (++tail == array.length) {
  38. tail = 0;
  39. }
  40. size++;
  41. //唤醒等待非空的线程
  42. headWaits.signal();
  43. } finally {
  44. lock.unlock();
  45. }
  46. }
  47. /*
  48. * 优化后的offer,设置等待时间,超出则抛出异常
  49. * */
  50. @Override
  51. public boolean offer(E e, long timeout) throws InterruptedException {
  52. lock.lockInterruptibly();
  53. try {
  54. //等待timeout纳秒抛出异常
  55. long ns = TimeUnit.MICROSECONDS.toNanos(timeout);
  56. while (isFull()) {
  57. if (ns <= 0) {
  58. return false;
  59. }
  60. ns = tailWaits.awaitNanos(ns);
  61. }
  62. array[tail] = e;
  63. if (++tail == array.length) {
  64. tail = 0;
  65. }
  66. size++;
  67. //唤醒等待非空的线程
  68. headWaits.signal();
  69. return true;
  70. } finally {
  71. lock.unlock();
  72. }
  73. }
  74. @Override
  75. public E pool() throws InterruptedException {
  76. lock.lockInterruptibly();
  77. try {
  78. while (isFull()) {
  79. headWaits.await();
  80. }
  81. E e = array[head];
  82. array[head] = null;
  83. if (++head == array.length) {
  84. head = 0;
  85. }
  86. size--;
  87. //唤醒等待不满的线程
  88. tailWaits.signal();
  89. return e;
  90. } finally {
  91. lock.unlock();
  92. }
  93. }
  94. public boolean isFull() {
  95. return size == array.length;
  96. }
  97. public boolean isEmpty() {
  98. return size == 0;
  99. }
  100. }

6.4.2 双锁实现

6.4.2.1 双锁实现1

由于tailWaits.signal();必须配合taillock.unlock(); taillock.unlock();使用,headloca也一样,这种方式极易出现死锁问题。

使用jps命令可以获取进程id,jstack+进程id 可以检测死锁等问题。

可以将两个锁列为平级,而不是嵌套即可解决。

  1. /*
  2. * 单锁实现方式,offer和pool是互相影响的,
  3. * 但是head指针和tail执行两者并不互相影响,
  4. * 会降低运行效率,offer和pool不应该互相影响
  5. * */
  6. public class BlockingQueue2<E> implements BlockingQueue<E> {
  7. public static void main(String[] args) {
  8. BlockingQueue2<String> blockingQueue2 = new BlockingQueue2<>(3);
  9. try {
  10. blockingQueue2.offer("任务1");
  11. blockingQueue2.offer("任务2");
  12. blockingQueue2.offer("任务3");
  13. boolean offer = blockingQueue2.offer("任务4", 2000);
  14. System.out.println(offer);
  15. } catch (InterruptedException e) {
  16. throw new RuntimeException(e);
  17. }
  18. }
  19. private final E[] array;
  20. private int head;
  21. private int tail;
  22. /*
  23. * 由于 pool和offer会同时操作size变量,
  24. * 所以size应该被声明为原子变量
  25. * */
  26. private AtomicInteger size=new AtomicInteger();
  27. private ReentrantLock taillock = new ReentrantLock();
  28. private ReentrantLock headlock = new ReentrantLock();
  29. /*
  30. * headlock和headWaits必须配合使用否则会报错
  31. * */
  32. private Condition tailWaits = taillock.newCondition();
  33. private Condition headWaits = headlock.newCondition();
  34. public BlockingQueue2(int capacity) {
  35. this.array = (E[]) new Object[capacity];
  36. }
  37. @Override
  38. public void offer(E e) throws InterruptedException {
  39. taillock.lockInterruptibly();
  40. try {
  41. //防止虚假唤醒
  42. while (isFull()) {
  43. tailWaits.await();
  44. }
  45. array[tail] = e;
  46. if (++tail == array.length) {
  47. tail = 0;
  48. }
  49. size.addAndGet(1);
  50. //唤醒等待非空的线程
  51. headWaits.signal();
  52. } finally {
  53. taillock.unlock();
  54. }
  55. }
  56. /*
  57. * 优化后的offer,设置等待时间,超出则抛出异常
  58. * */
  59. @Override
  60. public boolean offer(E e, long timeout) throws InterruptedException {
  61. taillock.lockInterruptibly();
  62. try {
  63. //等待timeout纳秒抛出异常
  64. long ns = TimeUnit.MICROSECONDS.toNanos(timeout);
  65. while (isFull()) {
  66. if (ns <= 0) {
  67. return false;
  68. }
  69. ns = tailWaits.awaitNanos(ns);
  70. }
  71. array[tail] = e;
  72. if (++tail == array.length) {
  73. tail = 0;
  74. }
  75. size.getAndIncrement();
  76. //唤醒等待非空的线程,必须配合headlocal使用
  77. headlock.lock();
  78. headWaits.signal();
  79. headlock.unlock();
  80. return true;
  81. } finally {
  82. taillock.unlock();
  83. }
  84. }
  85. @Override
  86. public E pool() throws InterruptedException {
  87. headlock.lockInterruptibly();
  88. try {
  89. while (isFull()) {
  90. headWaits.await();
  91. }
  92. E e = array[head];
  93. array[head] = null;
  94. if (++head == array.length) {
  95. head = 0;
  96. }
  97. size.getAndDecrement();
  98. //唤醒等待不满的线程,tailWaits闭合和tailLock配合使用
  99. taillock.unlock();
  100. tailWaits.signal();
  101. taillock.unlock();
  102. return e;
  103. } finally {
  104. headlock.unlock();
  105. }
  106. }
  107. public boolean isFull() {
  108. return size.get() == array.length;
  109. }
  110. public boolean isEmpty() {
  111. return size.get() == 0;
  112. }
  113. }
6.4.2.2 双锁实现2

为了提升效率应该尽量减少taillock和headlock之间的互相影响,对应的就可以提升效率,tail的唤醒操作只由第一个线程执行,而后续的唤醒可以交给第一个线程来执行,headlock也是一样的。这也叫做级联操作。

  1. /*
  2. * 单锁实现方式,offer和pool是互相影响的,
  3. * 但是head指针和tail执行两者并不互相影响,
  4. * 会降低运行效率,offer和pool不应该互相影响
  5. * */
  6. public class BlockingQueue2<E> implements BlockingQueue<E> {
  7. public static void main(String[] args) {
  8. BlockingQueue2<String> blockingQueue2 = new BlockingQueue2<>(3);
  9. try {
  10. blockingQueue2.offer("任务1");
  11. blockingQueue2.offer("任务2");
  12. blockingQueue2.offer("任务3");
  13. boolean offer = blockingQueue2.offer("任务4", 2000);
  14. System.out.println(offer);
  15. } catch (InterruptedException e) {
  16. throw new RuntimeException(e);
  17. }
  18. }
  19. private final E[] array;
  20. private int head;
  21. private int tail;
  22. /*
  23. * 由于 pool和offer会同时操作size变量,
  24. * 所以size应该被声明为原子变量
  25. * */
  26. private AtomicInteger size = new AtomicInteger();
  27. private ReentrantLock taillock = new ReentrantLock();
  28. private ReentrantLock headlock = new ReentrantLock();
  29. /*
  30. * headlock和headWaits必须配合使用否则会报错
  31. * */
  32. private Condition tailWaits = taillock.newCondition();
  33. private Condition headWaits = headlock.newCondition();
  34. public BlockingQueue2(int capacity) {
  35. this.array = (E[]) new Object[capacity];
  36. }
  37. @Override
  38. public void offer(E e) throws InterruptedException {
  39. taillock.lockInterruptibly();
  40. try {
  41. //防止虚假唤醒
  42. while (isFull()) {
  43. tailWaits.await();
  44. }
  45. array[tail] = e;
  46. if (++tail == array.length) {
  47. tail = 0;
  48. }
  49. size.addAndGet(1);
  50. //唤醒等待非空的线程,
  51. headWaits.signal();
  52. } finally {
  53. taillock.unlock();
  54. }
  55. }
  56. /*
  57. * 优化后的offer,设置等待时间,超出则抛出异常
  58. * */
  59. @Override
  60. public boolean offer(E e, long timeout) throws InterruptedException {
  61. //新增元素钱的个数,为0既说明是第一个线程
  62. int c;
  63. taillock.lockInterruptibly();
  64. try {
  65. //等待timeout纳秒抛出异常
  66. long ns = TimeUnit.MICROSECONDS.toNanos(timeout);
  67. while (isFull()) {
  68. if (ns <= 0) {
  69. return false;
  70. }
  71. ns = tailWaits.awaitNanos(ns);
  72. }
  73. array[tail] = e;
  74. if (++tail == array.length) {
  75. tail = 0;
  76. }
  77. c = size.getAndIncrement();
  78. // 如果c+1<arr.length说明还没有满,那么级联唤醒
  79. if(c+1< array.length){
  80. tailWaits.signal();
  81. }
  82. } finally {
  83. taillock.unlock();
  84. }
  85. try {
  86. //唤醒等待非空的线程,必须配合headlocal使用
  87. headlock.lock();
  88. if (c == 0) {
  89. //第一个线程
  90. headWaits.signal();
  91. }
  92. headlock.unlock();
  93. } catch (Exception exception) {
  94. throw exception;
  95. }
  96. return true;
  97. }
  98. @Override
  99. public E pool() throws InterruptedException {
  100. E e;
  101. //取走钱的元素个数
  102. int c;
  103. headlock.lockInterruptibly();
  104. try {
  105. while (isFull()) {
  106. headWaits.await();
  107. }
  108. e = array[head];
  109. array[head] = null;
  110. if (++head == array.length) {
  111. head = 0;
  112. }
  113. c = size.getAndDecrement();
  114. if (c > 1) {
  115. // 说明还有其他元素,唤醒下一个
  116. headWaits.signal();
  117. }
  118. } finally {
  119. headlock.unlock();
  120. }
  121. //唤醒等待不满的线程,tailWaits闭合和tailLock配合使用
  122. try {
  123. taillock.unlock();
  124. //唤醒减少之前队列是满的那个线程
  125. if (c == array.length) {
  126. tailWaits.signal();
  127. }
  128. taillock.unlock();
  129. } catch (Exception exception) {
  130. throw exception;
  131. }
  132. return e;
  133. }
  134. public boolean isFull() {
  135. return size.get() == array.length;
  136. }
  137. public boolean isEmpty() {
  138. return size.get() == 0;
  139. }
  140. }

 7.(数据结构)堆

7.1 相关概念

        堆(Heap)在计算机科学中是一种特殊的数据结构,它通常被实现为一个可以看作完全二叉树的数组对象。以下是一些关于堆的基本概念:

数据结构:

        堆是一个优先队列的抽象数据类型实现,通过完全二叉树的逻辑结构来组织元素。
完全二叉树意味着除了最后一层外,每一层都被完全填满,并且最后一层的所有节点都尽可能地集中在左边。
物理存储:

        堆用一维数组顺序存储,从索引0开始,每个节点的父节点和子节点之间的关系可以通过简单的算术运算确定。
堆的特性:

        堆序性质:对于任意节点i,其值(或关键字)满足与它的子节点的关系——在最大堆(大根堆)中,节点i的值大于或等于其两个子节点的值;在最小堆(小根堆)中,节点i的值小于或等于其两个子节点的值。
结构性:堆始终保持完全二叉树的状态,这意味着即使有节点删除或插入,堆也要经过调整以保持堆序性质。
操作:

        插入:新元素添加到堆中时,需要自下而上调整堆,以确保新的元素不会破坏堆的性质。
        删除:通常从堆顶(根节点)删除元素(即最大堆中的最大元素或最小堆中的最小元素),然后将堆尾元素移动到堆顶,再自上而下调整堆。
        查找:堆常用于快速找到最大或最小元素,但查找特定值的时间复杂度通常不优于线性时间,因为堆本身不具备随机访问的能力。
应用:

        堆常用于解决各种问题,如优先级队列、事件调度、图算法中的最短路径计算(Dijkstra算法)、求解Top K问题等。
分类:

        最常见的堆是二叉堆,包括大根堆和小根堆。
        还有其他类型的堆,比如斐波那契堆,提供更高效的合并操作以及其他优化特性。

建堆算法:

       1. Dijkstra算法:是一个使用优先队列(可以基于堆实现)的经典例子。在Dijkstra算法中,每次都会从未确定最短路径且当前距离已知最小的顶点开始,更新与其相邻顶点的距离。为了高效地找到下一个待处理的顶点(即当前已知最短路径的顶点),会用到一个能够根据顶点距离值进行快速插入和删除的优先队列,堆就是实现这种功能的理想数据结构之一。

       2. 堆下沉”(Heap Sink),“堆下滤”(Heap Percolate Down):从根节点(非叶子节点中最高层的一个)开始。 检查该节点与其两个子节点的关系:在最大堆中,如果当前节点的值小于其任意一个子节点的值;在最小堆中,如果当前节点的值大于其任意一个子节点的值。 如果违反了堆的性质,则交换当前节点与其较大(对于最大堆)或较小(对于最小堆)子节点的值,并将当前节点移动到新位置(即原来子节点的位置)。 重复上述步骤,但这次以交换后的子节点作为新的当前节点,继续下潜至当前节点没有子节点(即成为叶子节点),或者当前节点及其子节点均满足堆的性质为止。

时间复杂度:

7.2 大顶堆

堆内比较重要的方法就是,建堆,堆下潜操作,堆上浮操作

  1. /*
  2. * 大顶堆
  3. * */
  4. public class MaxHeap {
  5. public static void main(String[] args) {
  6. int[] array = {1, 2, 3, 4, 5, 6, 7};
  7. MaxHeap maxHeap = new MaxHeap(array);
  8. System.out.println(Arrays.toString(MaxHeap.array));
  9. }
  10. static int[] array;
  11. static int size;
  12. public MaxHeap(int[] array) {
  13. this.array = array;
  14. this.size = array.length;
  15. heapify();
  16. }
  17. /*
  18. * 建堆:
  19. * 找到第一个非叶子结点
  20. * 执行下潜,直到没有子节点
  21. * */
  22. private void heapify() {
  23. //最后一个非叶子结点 size/2-1
  24. for (int i = size / 2 - 1; i >= 0; i--) {
  25. down(i);
  26. }
  27. }
  28. //执行下潜 parent 为需要下潜的索引,下潜到没有孩子,或者孩子都小于当前节点
  29. private void down(int parent) {
  30. //左child索引
  31. int leftChild = parent * 2 + 1;
  32. //右child索引
  33. int rightChild = leftChild + 1;
  34. int max = parent;
  35. if (leftChild < size && array[max] < array[leftChild]) max = leftChild;
  36. if (rightChild < size && array[max] < array[rightChild]) max = rightChild;
  37. if (max != parent) {
  38. //下潜并再次调用
  39. swap(parent, max);
  40. down(max);
  41. }
  42. }
  43. /*
  44. * 上浮操作
  45. * */
  46. public void up(int offered){
  47. int child =size;
  48. //子元素索引等于0则到达了堆顶
  49. while (child>0){
  50. int parent=(child-1)/2;
  51. if (offered>array[parent]){
  52. array[child]=array[parent];
  53. }else {
  54. break;
  55. }
  56. child=parent;
  57. }
  58. array[child] = offered;
  59. }
  60. //交换两个元素
  61. private void swap(int i, int j) {
  62. isEmptyeException();
  63. int temp = array[i];
  64. array[i] = array[j];
  65. array[j] = temp;
  66. }
  67. public int peek(){
  68. isEmptyeException();
  69. return array[0];
  70. }
  71. /*
  72. * 从第一个位置移除元素,交换头尾,在移除最后一个
  73. * */
  74. public int poll(){
  75. isEmptyeException();
  76. int temp=array[0];
  77. //交换首位
  78. swap(0,size-1);
  79. size--;
  80. down(0);
  81. return temp;
  82. }
  83. /*
  84. * 从指定位置移除元素,交换指定位置和尾,在移除最后一个
  85. * */
  86. public int poll(int index){
  87. isEmptyeException();
  88. int temp=array[index];
  89. //交换首位
  90. swap(index,size-1);
  91. size--;
  92. down(index);
  93. return temp;
  94. }
  95. /*
  96. * 替换堆顶部元素
  97. * 1.替换堆顶元素
  98. * 2.执行下潜,直到符合堆的特性
  99. * */
  100. public void replace(int replaced){
  101. isEmptyeException();
  102. array[0]=replaced;
  103. down(0);
  104. }
  105. /*
  106. * 堆尾部添加元素
  107. * */
  108. public boolean offered(int offered){
  109. if(isFull()){
  110. return false;
  111. }
  112. up(offered);
  113. size++;
  114. return true;
  115. }
  116. /*
  117. * 堆满异常
  118. * */
  119. public void isFulleException(){
  120. if (isFull()){
  121. throw new RuntimeException("堆已满");
  122. }
  123. }
  124. /*
  125. * 堆空异常
  126. * */
  127. public void isEmptyeException(){
  128. if (isEmpty()){
  129. throw new RuntimeException("堆为空");
  130. }
  131. }
  132. /*
  133. * 判满
  134. * */
  135. public boolean isFull(){
  136. return size== array.length;
  137. }
  138. /*
  139. * 判空
  140. * */
  141. public boolean isEmpty(){
  142. return size== 0;
  143. }
  144. }

7.3 堆排序

        堆排序是一种基于比较的排序算法,它利用了完全二叉树(即堆)这种数据结构。堆通常可以分为两种:最大堆和最小堆。在最大堆中,父节点的值总是大于或等于其所有子节点的值;在最小堆中,父节点的值总是小于或等于其所有子节点的值。

堆排序的基本步骤如下:

        构造初始堆:首先将待排序的序列构造成一个大顶堆(升序排序)或小顶堆(降序排序)。从最后一个非叶子节点开始,自底向上、自右向左进行调整。

        堆调整:将堆顶元素(即当前未排序序列的最大元素或者最小元素)与末尾元素进行交换,然后移除末尾元素(因为它已经是最小或最大的),这样就完成了第一个元素的排序。此时,剩余未排序部分不再满足堆的性质,因此需要对剩余元素重新调整为堆。

        重复步骤2:对剩余的n-1个元素重新构造堆,再将堆顶元素与末尾元素交换并移除末尾元素,直到整个序列都有序。

        通过不断调整堆和交换堆顶元素,最终实现整个序列的排序。

        堆排序的时间复杂度为O(nlogn),其中n为待排序元素的数量,空间复杂度为O(1)(原地排序)。由于其在最坏情况下的时间复杂度依然为O(nlogn),且不需要额外的存储空间,因此堆排序在处理大数据量时具有较好的性能表现。

  1. public class HeapSort {
  2. public static void main(String[] args) {
  3. int[] array = {2, 3, 1, 7, 6, 4, 5};
  4. HeapSort heapSort = new HeapSort(array);
  5. System.out.println(Arrays.toString(heapSort.array));
  6. while (heapSort.size > 1) {
  7. heapSort.swap(0, heapSort.size-1);
  8. heapSort.size--;
  9. heapSort.down(0);
  10. }
  11. System.out.println(Arrays.toString(heapSort.array));
  12. }
  13. int[] array;
  14. int size;
  15. public HeapSort(int[] array) {
  16. this.array = array;
  17. this.size = array.length;
  18. heapify();
  19. }
  20. /*
  21. * 建堆:
  22. * 找到第一个非叶子结点
  23. * 执行下潜,直到没有子节点
  24. * */
  25. private void heapify() {
  26. //最后一个非叶子结点 size/2-1
  27. for (int i = size / 2 - 1; i >= 0; i--) {
  28. down(i);
  29. }
  30. }
  31. //执行下潜 parent 为需要下潜的索引,下潜到没有孩子,或者孩子都小于当前节点
  32. private void down(int parent) {
  33. //左child索引
  34. int leftChild = parent * 2 + 1;
  35. //右child索引
  36. int rightChild = leftChild + 1;
  37. int max = parent;
  38. if (leftChild < size && array[max] < array[leftChild]) max = leftChild;
  39. if (rightChild < size && array[max] < array[rightChild]) max = rightChild;
  40. if (max != parent) {
  41. //下潜并再次调用
  42. swap(parent, max);
  43. down(max);
  44. }
  45. }
  46. /*
  47. * 上浮操作
  48. * */
  49. public void up(int offered) {
  50. int child = size;
  51. //子元素索引等于0则到达了堆顶
  52. while (child > 0) {
  53. int parent = (child - 1) / 2;
  54. if (offered > array[parent]) {
  55. array[child] = array[parent];
  56. } else {
  57. break;
  58. }
  59. child = parent;
  60. }
  61. array[child] = offered;
  62. }
  63. //交换两个元素
  64. private void swap(int i, int j) {
  65. int temp = array[i];
  66. array[i] = array[j];
  67. array[j] = temp;
  68. }
  69. }

 8.二叉树

8.1概述

        二叉树是一种基本的非线性数据结构,它是由n(n>=0)个节点构成的有限集合。在二叉树中,每个节点最多有两个子节点,通常被称作左孩子(left child)和右孩子(right child)。此外,二叉树还具有以下特点: 每个节点包含一个值(也可以包含其他信息)。 有一个被称为根(root)的特殊节点,它是二叉树的起点,没有父节点。 如果一个节点存在左子节点,则该节点称为左子节点的父节点;同样,如果存在右子节点,则称为右子节点的父节点。 每个节点的所有子孙(包括子节点、孙子节点等)构成了该节点的子树(subtree)。 左子树和右子树本身也是二叉树,且可以为空。

 8.2 二叉树遍历

 遍历:

        广度优先遍历(Breadth-First Search, BFS)和深度优先遍历(Depth-First Search, DFS)是两种在图或树这类非线性数据结构中搜索节点的常用策略。

        广度优先遍历(BFS): 从根节点开始,首先访问所有与根节点直接相连的节点(即第一层邻居节点),然后按顺序访问它们的子节点(第二层),接着是孙子节点(第三层),以此类推。 使用队列作为辅助数据结构,将起始节点入队,每次从队列头部取出一个节点进行访问,并将其未被访问过的相邻节点全部加入队列尾部,直到队列为空为止。 在二叉树场景下,BFS通常实现为层序遍历,它会按照从上到下、从左到右的顺序依次访问各个节点。

        深度优先遍历(DFS): 从根节点开始,尽可能深地探索图或树的分支,直到到达叶子节点或者无法继续深入时返回上一层节点,再尝试探索其他分支。 深度优先遍历有多种方式:前序遍历(先访问根节点,再遍历左子树,最后遍历右子树)、中序遍历(先遍历左子树,再访问根节点,最后遍历右子树)、后序遍历(先遍历左子树,再遍历右子树,最后访问根节点)以及反向的前后序遍历等。 在二叉树的DFS中,通常使用递归的方式实现。另外,也可以借助栈这一数据结构,模拟递归过程进行非递归实现。 总结来说,BFS保证了同一层次的节点会被一起访问到,而DFS则是沿着一条路径尽可能深地探索,直至无法继续前进时回溯至另一条路径。这两种遍历方式在解决不同的问题时各有优势,如寻找最短路径、拓扑排序等场景常常会用到BFS,而解决迷宫求解、判断连通性等问题时DFS则更为常见。

 8.3 深度优先遍历

深度优先遍历(DFS)分为:

        前序遍历(Preorder Traversal): 在前序遍历中,访问顺序为:根节点 -> 左子树 -> 右子树。 递归地对当前节点的左子树进行前序遍历。 递归地对当前节点的右子树进行前序遍历。

        中序遍历(Inorder Traversal): 在中序遍历中,访问顺序为:左子树 -> 根节点 -> 右子树。 递归地对当前节点的左子树进行中序遍历。 访问当前节点。 递归地对当前节点的右子树进行中序遍历。

        后序遍历(Postorder Traversal): 在后序遍历中,访问顺序为:左子树 -> 右子树 -> 根节点。 递归地对当前节点的左子树进行后序遍历。 递归地对当前节点的右子树进行后序遍历。 访问当前节点。

8.3.1 递归实现遍历

  1. public class TreeTraversal {
  2. public static void main(String[] args) {
  3. TreeNode tree = new TreeNode(
  4. new TreeNode(new TreeNode(4), 2, null),
  5. 1,
  6. new TreeNode(new TreeNode(5), 3, new TreeNode(6)));
  7. preOrder(tree);
  8. System.out.println();
  9. inOrder(tree);
  10. System.out.println();
  11. postOrder(tree);
  12. System.out.println();
  13. }
  14. /*
  15. * 前序遍历 根节点=》左子树=》右子树
  16. * */
  17. //递归实现
  18. static void preOrder(TreeNode treeNode){
  19. if(treeNode==null){
  20. return;
  21. }
  22. System.out.print(treeNode.val+"\t");//根节点
  23. preOrder(treeNode.left);//左子树
  24. preOrder(treeNode.right);//右子树
  25. }
  26. /*
  27. * 中序遍历 左子树=》=》根节点=》右子树
  28. * */
  29. static void inOrder(TreeNode treeNode){
  30. if(treeNode==null){
  31. return;
  32. }
  33. inOrder(treeNode.left);//左子树
  34. System.out.print(treeNode.val+"\t");//根节点
  35. inOrder(treeNode.right);//右子树
  36. }
  37. /*
  38. * 后序遍历 左子树=》右子树 =》根节点
  39. * */
  40. static void postOrder(TreeNode treeNode){
  41. if(treeNode==null){
  42. return;
  43. }
  44. postOrder(treeNode.left);//左子树
  45. postOrder(treeNode.right);//右子树
  46. System.out.print(treeNode.val+"\t");//根节点
  47. }
  48. }

8.3.2 非递归实现遍历

  1. //非递归实现
  2. public class TreeTraversal2 {
  3. public static void main(String[] args) {
  4. TreeNode tree = new TreeNode(
  5. new TreeNode(new TreeNode(4), 2, null),
  6. 1,
  7. new TreeNode(new TreeNode(5), 3, new TreeNode(6)));
  8. preOrder(tree);
  9. System.out.println();
  10. inOrder(tree);
  11. System.out.println();
  12. postOrder(tree);
  13. System.out.println();
  14. }
  15. /*
  16. * 前序遍历 根节点=》左子树=》右子树
  17. * */
  18. static void preOrder(TreeNode treeNode){
  19. LinkedList<TreeNode> stack = new LinkedList<>();
  20. //定义一个指针,当前节点
  21. TreeNode curr = treeNode;
  22. //去的路径为前序遍历,回的路径为中序遍历
  23. while (curr != null||!stack.isEmpty()) {
  24. if (curr != null) {
  25. stack.push(curr);//压入栈,为了记住返回的路径
  26. System.out.print("前序" + curr.val + "\t");
  27. curr = curr.left;
  28. }else {
  29. TreeNode peek = stack.peek();
  30. TreeNode pop=stack.pop();
  31. curr= pop.right;
  32. }
  33. }
  34. }
  35. /*
  36. * 中序遍历 左子树=》=》根节点=》右子树
  37. * */
  38. static void inOrder(TreeNode treeNode){
  39. LinkedList<TreeNode> stack = new LinkedList<>();
  40. //定义一个指针,当前节点
  41. TreeNode curr = treeNode;
  42. //去的路径为前序遍历,回的路径为中序遍历
  43. while (curr != null||!stack.isEmpty()) {
  44. if (curr != null) {
  45. stack.push(curr);//压入栈,为了记住返回的路径
  46. curr = curr.left;
  47. }else {
  48. TreeNode peek = stack.peek();
  49. TreeNode pop=stack.pop();
  50. System.out.print("中序" + pop.val + "\t");
  51. curr= pop.right;
  52. }
  53. }
  54. }
  55. /*
  56. * 后序遍历 左子树=》右子树 =》根节点
  57. * */
  58. static void postOrder(TreeNode treeNode){
  59. LinkedList<TreeNode> stack = new LinkedList<>();
  60. //定义一个指针,当前节点
  61. TreeNode curr = treeNode;
  62. //去的路径为前序遍历,回的路径为中序遍历
  63. TreeNode pop = null;
  64. while (curr != null || !stack.isEmpty()) {
  65. if (curr != null) {
  66. stack.push(curr);//压入栈,为了记住返回的路径
  67. curr = curr.left;
  68. } else {
  69. TreeNode peek = stack.peek();
  70. //右子树为null,或者最近一次弹栈的元素与当前元素的右子树相等 说明全部子树都处理完了
  71. if (peek.right == null||peek.right==pop) {
  72. //最近一次弹栈的元素
  73. pop= stack.pop();
  74. System.out.print("后序" + pop.val + "\t");
  75. } else {
  76. curr = peek.right;
  77. }
  78. }
  79. }
  80. }
  81. }

8.3.2 非递归实现遍历2

  1. //非递归实现
  2. public class TreeTraversal3 {
  3. public static void main(String[] args) {
  4. TreeNode tree = new TreeNode(
  5. new TreeNode(new TreeNode(4), 2, null),
  6. 1,
  7. new TreeNode(new TreeNode(5), 3, new TreeNode(6)));
  8. postOrder(tree);
  9. System.out.println();
  10. }
  11. static void postOrder(TreeNode treeNode){
  12. LinkedList<TreeNode> stack = new LinkedList<>();
  13. //定义一个指针,当前节点
  14. TreeNode curr = treeNode;
  15. //去的路径为前序遍历,回的路径为中序遍历
  16. TreeNode pop = null;
  17. while (curr != null || !stack.isEmpty()) {
  18. if (curr != null) {
  19. //压入栈,为了记住返回的路径
  20. stack.push(curr);
  21. //待处理左子树
  22. System.out.println("前序"+curr.val);
  23. curr = curr.left;
  24. } else {
  25. TreeNode peek = stack.peek();
  26. //右子树为null,无需处理
  27. if (peek.right == null) {
  28. //最近一次弹栈的元素
  29. System.out.println("中序"+peek.val);
  30. pop= stack.pop();
  31. System.out.println("后序"+pop.val);
  32. }else if(peek.right==pop) {//最近一次弹栈的元素与当前元素的右子树相等 说明右子树都处理完了
  33. pop= stack.pop();
  34. System.out.println("后序"+pop.val);
  35. }else {
  36. //待处理右子树
  37. System.out.println("中序"+peek.val);
  38. curr = peek.right;
  39. }
  40. }
  41. }
  42. }
  43. }

9.二叉搜索树

9.1 概述

        二叉搜索树(Binary Search Tree,BST)是一种特殊的二叉树数据结构,其设计目的是为了支持高效的查找、插入和删除操作。在二叉搜索树中,每个节点都具有以下性质:

节点值的排序性:

        节点的左子树(如果存在)包含的所有节点的值都小于该节点的值。
节点的右子树(如果存在)包含的所有节点的值都大于该节点的值。
递归定义:

一个空树是二叉搜索树。
        如果一个非空树的根节点满足上述排序性,并且它的左子树和右子树分别都是二叉搜索树,则这个树整体上也是一个二叉搜索树。
操作特性:

        查找:通过比较待查找值与当前节点值来决定是向左子树还是右子树进行查找,可以将查找时间减少到对数级别(O(log n)),在最优情况下。
        插入:新插入的节点根据其值被放到合适的位置以保持树的排序性质。
        删除:删除节点可能涉及替换、移动或重新连接节点以维持树的完整性和排序规则。
        遍历顺序:

        中序遍历(Inorder Traversal):对于二叉搜索树来说,中序遍历的结果是一个递增排序的序列。
由于这些特点,二叉搜索树在计算机科学中广泛应用,特别是在需要频繁查询和更新动态集合的情况下,如数据库索引和文件系统等。

 9.2 get方法实现

9.2.1 普通get方法

  1. public class BSTree1 {
  2. BSTNode root;//根节点
  3. public BSTree1(BSTNode root) {
  4. this.root = root;
  5. }
  6. public BSTree1() {
  7. }
  8. //根据key查找相应的值 非递归实现
  9. public Object get(int key) {
  10. BSTNode node=root;
  11. while (node!=null){
  12. if(node.key>key){
  13. node=node.left;
  14. } else if (node.key<key) {
  15. node=node.right;
  16. }else{
  17. return node.value;
  18. }
  19. }
  20. return null;
  21. }
  22. //根据key查找相应的值 递归实现
  23. /*public Object get(int key) {
  24. return get(root, key);
  25. }
  26. public Object get(BSTNode node, int key) {
  27. if (node == null) {
  28. return null;
  29. }
  30. if (node.key > key) {
  31. return get(node.left, key);
  32. } else if (node.key < key) {
  33. return get(node.right, key);
  34. } else {
  35. return node.value;
  36. }
  37. }*/
  38. static class BSTNode {
  39. int key;
  40. Object value;
  41. BSTNode left;
  42. BSTNode right;
  43. public BSTNode(int key) {
  44. this.key = key;
  45. }
  46. public BSTNode(int key, Object value) {
  47. this.key = key;
  48. this.value = value;
  49. }
  50. public BSTNode(int key, Object value, BSTNode left, BSTNode right) {
  51. this.key = key;
  52. this.value = value;
  53. this.left = left;
  54. this.right = right;
  55. }
  56. }
  57. }

9.2.2 泛型key,value

只要具备比较大小功能的类都可以作为key,而具备比较大小功能只需要继承Comparable接口即可,value也可以用泛型来指定。

  1. public class BSTree2<T extends Comparable<T>,V> {
  2. BSTNode<T,V> root;//根节点
  3. public BSTree2(BSTNode root) {
  4. this.root = root;
  5. }
  6. public BSTree2() {
  7. }
  8. //泛型key 优化,接口必须继承Comparable
  9. public V get(T key){
  10. BSTNode<T,V> node=root;
  11. while (node!=null){
  12. int res = node.key.compareTo(key);
  13. if(res>0){
  14. node=node.left;
  15. } else if (res<0) {
  16. node=node.right;
  17. }else{
  18. return node.value;
  19. }
  20. }
  21. return null;
  22. }
  23. static class BSTNode<T,V> {
  24. T key;
  25. V value;
  26. BSTNode<T,V>left;
  27. BSTNode<T,V> right;
  28. public BSTNode(T key) {
  29. this.key = key;
  30. }
  31. public BSTNode(T key, V value) {
  32. this.key = key;
  33. this.value = value;
  34. }
  35. public BSTNode(T key, V value, BSTNode<T,V> left, BSTNode<T,V> right) {
  36. this.key = key;
  37. this.value = value;
  38. this.left = left;
  39. this.right = right;
  40. }
  41. }
  42. }

9.3 min,max方法实现

  1. public class BSTree3<T extends Comparable<T>, V> {
  2. BSTNode<T, V> root;//根节点
  3. public BSTree3(BSTNode root) {
  4. this.root = root;
  5. }
  6. public BSTree3() {
  7. }
  8. //非递归实现
  9. public V min() {
  10. BSTNode<T, V> curr = root;
  11. if(curr ==null) return null;
  12. while (curr.left != null) {
  13. curr = curr.left;
  14. }
  15. return curr.value;
  16. }
  17. public V max() {
  18. BSTNode<T, V> curr = root;
  19. if(curr ==null) return null;
  20. while (curr.right != null) {
  21. curr = curr.right;
  22. }
  23. return curr.value;
  24. }
  25. //递归实现
  26. /*public V min(){
  27. return min(root);
  28. }
  29. public V min(BSTNode<T,V> node){
  30. if(node ==null) return null;
  31. if(node.left!=null){
  32. return min(node.left);
  33. }else{
  34. return node.value;
  35. }
  36. }
  37. public V max(){
  38. return max(root);
  39. }
  40. public V max(BSTNode<T,V> node){
  41. if(node ==null) return null;
  42. if(node.right!=null){
  43. return max(node.right);
  44. }else{
  45. return node.value;
  46. }
  47. }*/
  48. static class BSTNode<T, V> {
  49. T key;
  50. V value;
  51. BSTNode<T, V> left;
  52. BSTNode<T, V> right;
  53. public BSTNode(T key) {
  54. this.key = key;
  55. }
  56. public BSTNode(T key, V value) {
  57. this.key = key;
  58. this.value = value;
  59. }
  60. public BSTNode(T key, V value, BSTNode<T, V> left, BSTNode<T, V> right) {
  61. this.key = key;
  62. this.value = value;
  63. this.left = left;
  64. this.right = right;
  65. }
  66. }
  67. }

9.4 put方法实现

  1. //put
  2. public class BSTree4<T extends Comparable<T>, V> {
  3. BSTNode<T, V> root;//根节点
  4. public BSTree4(BSTNode root) {
  5. this.root = root;
  6. }
  7. public BSTree4() {
  8. }
  9. /*
  10. * 有该节点,更新value,没有则新增
  11. * */
  12. public void put(T key,V value){
  13. BSTNode<T,V>node=root;
  14. BSTNode<T,V>parent=node;
  15. while (node!=null){
  16. parent=node;
  17. int res = node.key.compareTo(key);
  18. if(res>0){
  19. node=node.left;
  20. } else if (res<0) {
  21. node=node.right;
  22. }else{
  23. node.value=value;
  24. return;
  25. }
  26. }
  27. //没找到新增节点
  28. BSTNode<T,V>newNode=new BSTNode<>(key,value);
  29. //树为空
  30. if(parent==null){
  31. root=newNode;
  32. return;
  33. }
  34. int res = parent.key.compareTo(key);
  35. if(res>0){
  36. parent.left=newNode;
  37. }else if(res<0){
  38. parent.right=newNode;
  39. }
  40. }
  41. static class BSTNode<T, V> {
  42. T key;
  43. V value;
  44. BSTNode<T, V> left;
  45. BSTNode<T, V> right;
  46. public BSTNode(T key) {
  47. this.key = key;
  48. }
  49. public BSTNode(T key, V value) {
  50. this.key = key;
  51. this.value = value;
  52. }
  53. public BSTNode(T key, V value, BSTNode<T, V> left, BSTNode<T, V> right) {
  54. this.key = key;
  55. this.value = value;
  56. this.left = left;
  57. this.right = right;
  58. }
  59. }
  60. }

9.5 前任 后继方法实现

        对于一般的二叉搜索树来说,其特性是左子树的所有节点值都小于根节点,右子树的所有节点值都大于根节点。 我们首先需要找到目标节点。
 

        然后从目标节点开始回溯到其父节点,如果目标节点是其父节点的左孩子,则其“前任”就是其父节点;

        如果不是(即目标节点是其父节点的右孩子),则继续向上回溯至其父节点的父节点,重复此过程。

   如果在回溯过程中,我们到达了根节点且根节点是目标节点的父节点,并且目标节点是其右孩子,那么说明目标节点没有“前任”。

前任:

        如果目标有左子树,此时前任就是左子树的最大值。

        如果目标没有左子树,离他最近的自左而来的祖先就是他的前任。

     

后继:

        如果目标有右子树,此时前任就是右子树的最小值。

        如果目标没有右子树,离他最近的自右而来的祖先就是他的前任。

  1. //前任后继
  2. public class BSTree5<T extends Comparable<T>, V> {
  3. BSTNode<T, V> root;//根节点
  4. public BSTree5(BSTNode root) {
  5. this.root = root;
  6. }
  7. public BSTree5() {
  8. }
  9. /*
  10. * 如果目标有左子树,此时前任就是左子树的最大值。
  11. * 如果目标没有左子树,离他最近的自左而来的祖先就是他的前任。
  12. * */
  13. public V successor(T key) {
  14. BSTNode<T, V> curr = root;
  15. BSTNode<T, V> leftAncestor = null;
  16. while (curr != null) {
  17. int res = key.compareTo(curr.key);
  18. if (res < 0) {
  19. curr = curr.left;
  20. } else if (res > 0) {
  21. leftAncestor=curr;
  22. curr = curr.right;
  23. } else {
  24. //curr为查找到的节点
  25. break;
  26. }
  27. }
  28. //未找到
  29. if(curr==null){
  30. return null;
  31. }
  32. //有左子树
  33. if(curr.left!=null){
  34. curr=curr.left;
  35. while (curr.right!=null){
  36. curr=curr.right;
  37. }
  38. return curr.value;
  39. }
  40. //节点没有左子树
  41. return leftAncestor==null?null:leftAncestor.value;
  42. }
  43. /*
  44. * 如果目标有右子树,此时前任就是右子树的最大值。
  45. * 如果目标没有右子树,离他最近的自右而来的祖先就是他的前任。
  46. * */
  47. public V predecessor(T key){
  48. BSTNode<T, V> curr = root;
  49. BSTNode<T, V> rightAncestor = null;
  50. while (curr != null) {
  51. int res = key.compareTo(curr.key);
  52. if (res < 0) {
  53. rightAncestor=curr;
  54. curr = curr.left;
  55. } else if (res > 0) {
  56. curr = curr.right;
  57. } else {
  58. //curr为查找到的节点
  59. break;
  60. }
  61. }
  62. //未找到
  63. if(curr==null){
  64. return null;
  65. }
  66. //有左子树
  67. if(curr.right!=null){
  68. curr=curr.right;
  69. while (curr.left!=null){
  70. curr=curr.left;
  71. }
  72. return curr.value;
  73. }
  74. //节点没有左子树
  75. return rightAncestor==null?null:rightAncestor.value;
  76. }
  77. static class BSTNode<T, V> {
  78. T key;
  79. V value;
  80. BSTNode<T, V> left;
  81. BSTNode<T, V> right;
  82. public BSTNode(T key) {
  83. this.key = key;
  84. }
  85. public BSTNode(T key, V value) {
  86. this.key = key;
  87. this.value = value;
  88. }
  89. public BSTNode(T key, V value, BSTNode<T, V> left, BSTNode<T, V> right) {
  90. this.key = key;
  91. this.value = value;
  92. this.left = left;
  93. this.right = right;
  94. }
  95. }
  96. }

9.6 删除方法实现

1.删除没有子节点的节点:如果要删除的节点没有子节点,那么可以直接删除该节点,并将其父节点指向该节点的引用设置为 None。

2.删除只有一个子节点的节点:如果要删除的节点只有一个子节点(左或右)。

        2.1 删除元素为父元素左子结点:子节点作为父元素的左子结点。

        2.2 删除元素为父元素右子结点:子节点作为父元素的右子结点。

3.删除有两个子节点的节点:让被删除节点的后继节点顶替当前节点,分为两种

        3.1 后继节点为删除节点的直接子节点:直接顶替删除节点即可。

        3.2 后继节点非删除节点的直接子节点:要将后任节点的子节点交给后继节点的父节点,然后用后继节点顶替被删除节点。

9.6.1 非递归实现

  1. //删除节点
  2. public class BSTree6<T extends Comparable<T>, V> {
  3. BSTNode<T, V> root;//根节点
  4. public BSTree6(BSTNode root) {
  5. this.root = root;
  6. }
  7. public BSTree6() {
  8. }
  9. public V delete(T key) {
  10. BSTNode<T, V> curr = root;
  11. // 父节点
  12. BSTNode<T, V> parent = null;
  13. while (curr != null) {
  14. int res = key.compareTo(curr.key);
  15. if (res < 0) {
  16. parent = curr;
  17. curr = curr.left;
  18. } else if (res > 0) {
  19. parent = curr;
  20. curr = curr.right;
  21. } else {
  22. //curr为查找到的节点
  23. break;
  24. }
  25. }
  26. //未找到
  27. if (curr == null) {
  28. return null;
  29. }
  30. //删除操作
  31. if (curr.left == null) {
  32. //有右子节点,没有左子节点 将元素托管给父元素
  33. shift(parent, curr, curr.right);
  34. } else if (curr.left != null) {
  35. //有左子节点,没有右子节点 将元素托管给父元素
  36. shift(parent, curr, curr.left);
  37. } else {
  38. //左右子节点都存在
  39. // 1.查找被删除节点后继节点
  40. BSTNode<T, V> proNode = curr.right;
  41. BSTNode<T, V> sParent = curr;
  42. while (proNode != null) {
  43. //保存父节点信息
  44. sParent = proNode;
  45. //找到右子树最小值,没有left属性的元素
  46. proNode = proNode.left;
  47. }
  48. // 2.处理被删除节点后继节点的情况后
  49. // 2.1继节点为被删除元素的直接子节点(直接替换)
  50. // 2.2继节点为被删除元素的非直接子节点 将后任节点的子节点交给后继节点的父节点
  51. if (sParent != curr) {
  52. //删除后继节点并将后继节点右侧节点托管给后继节点的父节点(因为查找后继节点的操作,不断像left查找,不可能存在左侧节点)
  53. shift(sParent, proNode, proNode.right);
  54. //还要将被删除节点的右侧节点托管给后继节点
  55. proNode.right=curr.right;
  56. }
  57. // 3.用后继节点替换被删除节点(删除当前节点将后继节点托管给父节点)
  58. shift(parent, curr, proNode);
  59. //将被删除节点的左侧节点托管给后继节点
  60. proNode.left = curr.left;
  61. }
  62. return curr.value;
  63. }
  64. private void shift(BSTNode<T, V> parent, BSTNode<T, V> curr, BSTNode<T, V> child) {
  65. if (parent == null) {
  66. //被删除节点没有父元素
  67. root = curr;
  68. } else if (curr == parent.left) {
  69. //删除节点为父节点的左孩子
  70. parent.left = child;
  71. } else {
  72. //删除节点为父节点的右孩子
  73. parent.right = child;
  74. }
  75. }
  76. static class BSTNode<T, V> {
  77. T key;
  78. V value;
  79. BSTNode<T, V> left;
  80. BSTNode<T, V> right;
  81. public BSTNode(T key) {
  82. this.key = key;
  83. }
  84. public BSTNode(T key, V value) {
  85. this.key = key;
  86. this.value = value;
  87. }
  88. public BSTNode(T key, V value, BSTNode<T, V> left, BSTNode<T, V> right) {
  89. this.key = key;
  90. this.value = value;
  91. this.left = left;
  92. this.right = right;
  93. }
  94. }
  95. }

9.6.2 递归实现

  1. //删除节点 非递归
  2. public class BSTree6<T extends Comparable<T>, V> {
  3. BSTNode<T, V> root;//根节点
  4. public BSTree6(BSTNode root) {
  5. this.root = root;
  6. }
  7. public BSTree6() {
  8. }
  9. public V delete(T key) {
  10. ArrayList<V> arrayList = new ArrayList<>();
  11. root = delete(key, root, arrayList);
  12. return arrayList.isEmpty() ? null : arrayList.get(0);
  13. }
  14. private BSTNode delete(T key, BSTNode<T, V> node, ArrayList<V> arrayList) {
  15. if (node == null) {
  16. return null;
  17. }
  18. int res = key.compareTo(node.key);
  19. if (res < 0) {
  20. //当前节点的左侧子元素更新为删除结束后剩下的元素
  21. node.left = delete(key, node.left, arrayList);
  22. return node;
  23. }
  24. if (res > 0) {
  25. node.right = delete(key, node.right, arrayList);
  26. return node;
  27. }
  28. arrayList.add(node.value);
  29. //只有右子元素
  30. if (node.left == null) {
  31. return node.right;
  32. }
  33. //只有左子元素
  34. if (node.right == null) {
  35. return node.left;
  36. }
  37. //有两个子元素
  38. //删除节点与后继节点相邻
  39. BSTNode<T, V> s = node.left;
  40. BSTNode<T, V> sParent = node;
  41. while (s.left != node) {
  42. s = s.left;
  43. }
  44. //删除节点与后继节点不相邻
  45. s.right = delete(s.key, node.right, new ArrayList<>());
  46. //更新后继节点的左子元素为删除节点的左子元素
  47. s.left = node.left;
  48. return s;
  49. }
  50. private void shift(BSTNode<T, V> parent, BSTNode<T, V> curr, BSTNode<T, V> child) {
  51. if (parent == null) {
  52. //被删除节点没有父元素
  53. root = curr;
  54. } else if (curr == parent.left) {
  55. //删除节点为父节点的左孩子
  56. parent.left = child;
  57. } else {
  58. //删除节点为父节点的右孩子
  59. parent.right = child;
  60. }
  61. }
  62. static class BSTNode<T, V> {
  63. T key;
  64. V value;
  65. BSTNode<T, V> left;
  66. BSTNode<T, V> right;
  67. public BSTNode(T key) {
  68. this.key = key;
  69. }
  70. public BSTNode(T key, V value) {
  71. this.key = key;
  72. this.value = value;
  73. }
  74. public BSTNode(T key, V value, BSTNode<T, V> left, BSTNode<T, V> right) {
  75. this.key = key;
  76. this.value = value;
  77. this.left = left;
  78. this.right = right;
  79. }
  80. }
  81. }

9.7 范围查询

利用中序遍历,从小到大遍历,将符合条件的值添加到List中:

  1. //范围查询
  2. public class BSTree8<T extends Comparable<T>, V> {
  3. BSTNode<T, V> root;//根节点
  4. public BSTree8(BSTNode root) {
  5. this.root = root;
  6. }
  7. public BSTree8() {
  8. }
  9. /*
  10. * 中序遍历可以得到由小到大的结果
  11. * 判断与key的关系添加到list内
  12. * 将list返回
  13. * */
  14. //查找小于key
  15. public ArrayList<V> less(T key){
  16. ArrayList<V>res=new ArrayList<>();
  17. BSTNode<T,V>p=root;
  18. LinkedList<BSTNode<T,V>> stack=new LinkedList();
  19. while (p!=null || !stack.isEmpty()){
  20. if(p!=null){
  21. //未走到最左
  22. stack.push(p);
  23. p=p.left;
  24. }else{
  25. //到头之后弹栈
  26. BSTNode<T, V> pop = stack.pop();
  27. //处理值
  28. int popRes = pop.key.compareTo(key);
  29. if(popRes<0){
  30. res.add(pop.value);
  31. }else {
  32. break;
  33. }
  34. //弹出之后走右侧节点
  35. p=pop.right;
  36. }
  37. }
  38. return res;
  39. }
  40. //查找大于key
  41. public ArrayList<V> greater(T key){
  42. ArrayList<V>res=new ArrayList<>();
  43. BSTNode<T,V>p=root;
  44. LinkedList<BSTNode<T,V>> stack=new LinkedList();
  45. while (p!=null || !stack.isEmpty()){
  46. if(p!=null){
  47. //未走到最左
  48. stack.push(p);
  49. p=p.left;
  50. }else{
  51. //到头之后弹栈
  52. BSTNode<T, V> pop = stack.pop();
  53. //处理值
  54. int popRes = pop.key.compareTo(key);
  55. if(popRes>0){
  56. res.add(pop.value);
  57. }
  58. //弹出之后走右侧节点
  59. p=pop.right;
  60. }
  61. }
  62. return res;
  63. }
  64. //查找大于等于key1,小于等于key2
  65. public ArrayList<V> between(T key1,T key2){
  66. ArrayList<V>res=new ArrayList<>();
  67. BSTNode<T,V>p=root;
  68. LinkedList<BSTNode<T,V>> stack=new LinkedList();
  69. while (p!=null || !stack.isEmpty()){
  70. if(p!=null){
  71. //未走到最左
  72. stack.push(p);
  73. p=p.left;
  74. }else{
  75. //到头之后弹栈
  76. BSTNode<T, V> pop = stack.pop();
  77. //处理值
  78. int popRes1 = pop.key.compareTo(key1);
  79. int popRes2 = pop.key.compareTo(key2);
  80. if(popRes1>0 && popRes2<0){
  81. res.add(pop.value);
  82. }
  83. //弹出之后走右侧节点
  84. p=pop.right;
  85. }
  86. }
  87. return res;
  88. }
  89. static class BSTNode<T, V> {
  90. T key;
  91. V value;
  92. BSTNode<T, V> left;
  93. BSTNode<T, V> right;
  94. public BSTNode(T key) {
  95. this.key = key;
  96. }
  97. public BSTNode(T key, V value) {
  98. this.key = key;
  99. this.value = value;
  100. }
  101. public BSTNode(T key, V value, BSTNode<T, V> left, BSTNode<T, V> right) {
  102. this.key = key;
  103. this.value = value;
  104. this.left = left;
  105. this.right = right;
  106. }
  107. }
  108. }

10.AVL树

AVL 树(平衡二叉搜索树)
        二叉搜索树在插入和删除时,节点可能失衡
        如果在插入和删除时通过旋转,始终让二叉搜索树保持平衡,称为自平衡的二叉搜索树
        AVL是自平衡二又搜索树的实现之一

        如果一个节点的左右孩子,高度差超过1,则此节点失衡,才需要旋转。

10.1 获取高度

  1. //处理节点高度
  2. private int haight(AVLNode node) {
  3. return node == null ? 0 : node.height;
  4. }

10.2更新高度

  1. //增、删、旋转更新节点高度
  2. //最大高度+1
  3. public void updateHeight(AVLNode treeNode) {
  4. treeNode.height=Integer.max(haight(treeNode.left),haight(treeNode.right))+1;
  5. }

10.1 旋转

10.1.1 平衡因子

平衡因子:一个节点左子树高度-右子树高度所得结果
 小于1平衡:(0,1,-1)
 大于1不平衡
       >1:左边高
       <-1:右边高

        

  1. public int bf(AVLNode avlNode){
  2. return haight(avlNode.left)-haight(avlNode.right);
  3. }

10.1.2 四种失衡情况

 LL
    -失衡节点的 bf >1,即左边更高
    -失衡节点的左孩子的bf>=0即左孩子这边也是左边更高或等
    一次右旋可以恢复平衡
 LR
    -失衡节点的 bf >1,即左边更高
    -失衡节点的左孩子的bf<0 即左孩子这边是右边更高
    左子节点先左旋,将树修正为LL情况,
    然后失衡节点再右旋,恢复平衡
RL
    -失衡节点的 bf <-1,即右边更高
    -失衡节点的右孩子的bf>0,即右孩子这边左边更高
    右子节点先右旋,将树修正为RR情况,
    然后失衡节点再左旋,恢复平衡
 RR
    -失衡节点的 bf<-1,即右边更高
    -失衡节点的右孩子的bf<=0,即右孩子这边右边更高或等高
    一次左旋可以恢复平衡
  1. //右旋
  2. /**
  3. * @Description 返回旋转后的节点
  4. * @Param [avlNode] 需要旋转的节点
  5. **/
  6. private AVLNode rightRotate(AVLNode redNode) {
  7. AVLNode yellowNode = redNode.left;
  8. /*
  9. *黄色节点有右子节点,给右子节点重新找父级节点
  10. *由于二叉搜索树特性,某个节点的左子节点必定小于 本身,右子节点必定大于本身
  11. * 故:yelllow的右子节点必定大于yellow且小于rea,
  12. * 所以,gree可以作为red的左子结点
  13. * */
  14. /*
  15. AVLNode greeNode = yellowNode.right;
  16. redNode.left = greeNode;
  17. */
  18. redNode.left = yellowNode.right;
  19. yellowNode.right = redNode;
  20. //更新高度,红色和黄色都会改变
  21. updateHeight(redNode);
  22. updateHeight(yellowNode);
  23. return yellowNode;
  24. }
  25. //左旋
  26. private AVLNode leftRotate(AVLNode redNode) {
  27. //左旋和右旋操作相反
  28. AVLNode yellowNode = redNode.right;
  29. //处理yellow的子节点
  30. redNode.right = yellowNode.left;
  31. //yellow变为跟,原red比yellow小,为yellow的left
  32. yellowNode.left=redNode;
  33. updateHeight(redNode);
  34. updateHeight(yellowNode);
  35. return yellowNode;
  36. }
  37. /*
  38. * LR
  39. -失衡节点的 bf >1,即左边更高
  40. -失衡节点的左孩子的bf<0 即左孩子这边是右边更高
  41. 左子节点先左旋,将树修正为LL情况,
  42. 然后失衡节点再右旋,恢复平衡
  43. * */
  44. //先左旋再右旋
  45. private AVLNode leftRightRotate(AVLNode node) {
  46. //修正左子结点LL
  47. node.left = leftRotate(node.left);
  48. return rightRotate(node);
  49. }
  50. /*
  51. * RL
  52. -失衡节点的 bf <-1,即右边更高
  53. -失衡节点的右孩子的bf>0,即右孩子这边左边更高
  54. 右子节点先右旋,将树修正为RR情况,
  55. 然后失衡节点再左旋,恢复平衡
  56. * */
  57. //先右旋再左旋
  58. private AVLNode rightLeftRotate(AVLNode node) {
  59. //修正右子节点为RR
  60. node.right= rightRotate(node.left);
  61. return leftRotate(node);
  62. }

10.1.3 返回一个平衡后的树

  1. //检查节点是否失衡,重新平衡
  2. private AVLNode checkBalance(AVLNode node) {
  3. if (node == null) {
  4. return null;
  5. }
  6. //获取该节点的平衡因子
  7. int bf = bf(node);
  8. if (bf > 1) {
  9. //左边更高的两种情况根据 左子树平衡因子判定
  10. int leftBf = bf(node.left);
  11. if (leftBf >= 0) {
  12. //左子树左边高 LL 右旋 考虑到删除时等于0也应该右旋
  13. return rightRotate(node);
  14. } else {
  15. //左子树右边更高 LR
  16. return leftRightRotate(node);
  17. }
  18. } else if (bf < -1) {
  19. int rightBf = bf(node.right);
  20. if (rightBf <= 0) {
  21. //右子树左边更高 RR 虑到删除时等于0也要左旋
  22. return leftRotate(node);
  23. } else {
  24. //右子树右边更高 RL
  25. return rightLeftRotate(node);
  26. }
  27. }
  28. return node;
  29. }

10.2 新增

  1. public void put(int key, Object value){
  2. doPut(root,key,value);
  3. }
  4. //找空位并添加新的节点
  5. private AVLNode doPut(AVLNode node, int key, Object value) {
  6. /*
  7. * 1.找到空位,创建新节点
  8. * 2.key 已存在 更新位置
  9. * 3.继续寻找
  10. * */
  11. //未找到
  12. if (node ==null){
  13. return new AVLNode(key,value);
  14. }
  15. //找到了节点 重新赋值
  16. if(key ==node.key){
  17. node.value=value;
  18. return node;
  19. }
  20. //继续查找
  21. if(key < node.key){
  22. //继续向左,并建立父子关系
  23. node.left= doPut(node.left,key,value);
  24. }else{
  25. //向右找,并建立父子关系
  26. node.right= doPut(node.right,key,value);
  27. }
  28. //更新节点高度
  29. updateHeight(node);
  30. //重新平衡树
  31. return checkBalance(node);
  32. }

10.3 删除

  1. //删除
  2. public void remove(int key) {
  3. root = doRemove(root, key);
  4. }
  5. private AVLNode doRemove(AVLNode node, int key) {
  6. //1. node==null
  7. if (node == null) {
  8. return node;
  9. }
  10. //2.未找到key
  11. if (key < node.key) {
  12. //未找到key,且key小于当前节点key,继续向左
  13. node.left = doRemove(node.left, key);
  14. } else if (key > node.key) {
  15. //向右找
  16. node.right = doRemove(node.right, key);
  17. } else {
  18. //3.找到key
  19. if (node.left == null && node.right == null) {
  20. //3.1 没有子节点
  21. return null;
  22. } else if (node.left != null && node.right == null) {
  23. //3.2 一个子节点(左节点)
  24. node = node.left;
  25. } else if (node.left == null && node.right != null) {
  26. //3.2 一个子节点(右节点)
  27. node = node.right;
  28. } else {
  29. //3.3 两个子节点
  30. //找到他最小的后继节点,右子树向左找到底
  31. AVLNode s=node;
  32. while (s.left!=null){
  33. s=s.left;
  34. }
  35. //s即为后继节点,将节点删除并重新修正右子树
  36. s.right=doRemove(s.right,s.key);
  37. //左子树为s.left,右子树为原删除节点的左子树
  38. s.left=node.left;
  39. node=s;
  40. }
  41. }
  42. //4.更新高度
  43. updateHeight(node);
  44. //5.检查是否失衡
  45. return checkBalance(node);
  46. }

10.4 整体代码

  1. package org.alogorithm.tree.AVLTree;
  2. public class AVLTree {
  3. static class AVLNode {
  4. int key;
  5. int height = 1;//高度初始值1
  6. AVLNode left, right;
  7. private AVLNode root;
  8. Object value;
  9. public AVLNode(int key, Object value) {
  10. this.key = key;
  11. this.value = value;
  12. }
  13. public AVLNode(int key, AVLNode left, AVLNode right, AVLNode root) {
  14. this.key = key;
  15. this.left = left;
  16. this.right = right;
  17. this.root = root;
  18. }
  19. }
  20. //处理节点高度
  21. private int haight(AVLNode node) {
  22. return node == null ? 0 : node.height;
  23. }
  24. //增、删、旋转更新节点高度
  25. //最大高度+1
  26. public void updateHeight(AVLNode treeNode) {
  27. treeNode.height = Integer.max(haight(treeNode.left), haight(treeNode.right)) + 1;
  28. }
  29. /*
  30. 平衡因子:一个节点左子树高度-右子树高度所得结果
  31. 小于1平衡:(0,1,-1)
  32. 大于1不平衡
  33. >1:左边高
  34. <-1:右边高
  35. */
  36. public int bf(AVLNode avlNode) {
  37. return haight(avlNode.left) - haight(avlNode.right);
  38. }
  39. //四种失衡情况
  40. /*
  41. LL
  42. -失衡节点的 bf >1,即左边更高
  43. -失衡节点的左孩子的bf>=0即左孩子这边也是左边更高或等
  44. 一次右旋可以恢复平衡
  45. LR
  46. -失衡节点的 bf >1,即左边更高
  47. -失衡节点的左孩子的bf<0 即左孩子这边是右边更高
  48. 左子节点先左旋,将树修正为LL情况,
  49. 然后失衡节点再右旋,恢复平衡
  50. RL
  51. -失衡节点的 bf <-1,即右边更高
  52. -失衡节点的右孩子的bf>0,即右孩子这边左边更高
  53. 右子节点先右旋,将树修正为RR情况,
  54. 然后失衡节点再左旋,恢复平衡
  55. RR
  56. -失衡节点的 bf<-1,即右边更高
  57. -失衡节点的右孩子的bf<=0,即右孩子这边右边更高或等高
  58. 一次左旋可以恢复平衡
  59. */
  60. //右旋
  61. /**
  62. * @Description 返回旋转后的节点
  63. * @Param [avlNode] 需要旋转的节点
  64. **/
  65. private AVLNode rightRotate(AVLNode redNode) {
  66. AVLNode yellowNode = redNode.left;
  67. /*
  68. *黄色节点有右子节点,给右子节点重新找父级节点
  69. *由于二叉搜索树特性,某个节点的左子节点必定小于 本身,右子节点必定大于本身
  70. * 故:yelllow的右子节点必定大于yellow且小于rea,
  71. * 所以,gree可以作为red的左子结点
  72. * */
  73. /*
  74. AVLNode greeNode = yellowNode.right;
  75. redNode.left = greeNode;
  76. */
  77. redNode.left = yellowNode.right;
  78. yellowNode.right = redNode;
  79. //更新高度,红色和黄色都会改变
  80. updateHeight(redNode);
  81. updateHeight(yellowNode);
  82. return yellowNode;
  83. }
  84. //左旋
  85. private AVLNode leftRotate(AVLNode redNode) {
  86. //左旋和右旋操作相反
  87. AVLNode yellowNode = redNode.right;
  88. //处理yellow的子节点
  89. redNode.right = yellowNode.left;
  90. //yellow变为跟,原red比yellow小,为yellow的left
  91. yellowNode.left = redNode;
  92. updateHeight(redNode);
  93. updateHeight(yellowNode);
  94. return yellowNode;
  95. }
  96. /*
  97. * LR
  98. -失衡节点的 bf >1,即左边更高
  99. -失衡节点的左孩子的bf<0 即左孩子这边是右边更高
  100. 左子节点先左旋,将树修正为LL情况,
  101. 然后失衡节点再右旋,恢复平衡
  102. * */
  103. //先左旋再右旋
  104. private AVLNode leftRightRotate(AVLNode node) {
  105. //修正左子结点LL
  106. node.left = leftRotate(node.left);
  107. return rightRotate(node);
  108. }
  109. /*
  110. * RL
  111. -失衡节点的 bf <-1,即右边更高
  112. -失衡节点的右孩子的bf>0,即右孩子这边左边更高
  113. 右子节点先右旋,将树修正为RR情况,
  114. 然后失衡节点再左旋,恢复平衡
  115. * */
  116. //先右旋再左旋
  117. private AVLNode rightLeftRotate(AVLNode node) {
  118. //修正右子节点为RR
  119. node.right = rightRotate(node.left);
  120. return leftRotate(node);
  121. }
  122. //检查节点是否失衡,重新平衡
  123. private AVLNode checkBalance(AVLNode node) {
  124. if (node == null) {
  125. return null;
  126. }
  127. //获取该节点的平衡因子
  128. int bf = bf(node);
  129. if (bf > 1) {
  130. //左边更高的两种情况根据 左子树平衡因子判定
  131. int leftBf = bf(node.left);
  132. if (leftBf >= 0) {
  133. //左子树左边高 LL 右旋 考虑到删除时等于0也应该右旋
  134. return rightRotate(node);
  135. } else {
  136. //左子树右边更高 LR
  137. return leftRightRotate(node);
  138. }
  139. } else if (bf < -1) {
  140. int rightBf = bf(node.right);
  141. if (rightBf <= 0) {
  142. //右子树左边更高 RR 虑到删除时等于0也要左旋
  143. return leftRotate(node);
  144. } else {
  145. //右子树右边更高 RL
  146. return rightLeftRotate(node);
  147. }
  148. }
  149. return node;
  150. }
  151. AVLNode root;
  152. public void put(int key, Object value) {
  153. doPut(root, key, value);
  154. }
  155. //找空位并添加新的节点
  156. private AVLNode doPut(AVLNode node, int key, Object value) {
  157. /*
  158. * 1.找到空位,创建新节点
  159. * 2.key 已存在 更新位置
  160. * 3.继续寻找
  161. * */
  162. //未找到
  163. if (node == null) {
  164. return new AVLNode(key, value);
  165. }
  166. //找到了节点 重新赋值
  167. if (key == node.key) {
  168. node.value = value;
  169. return node;
  170. }
  171. //继续查找
  172. if (key < node.key) {
  173. //继续向左,并建立父子关系
  174. node.left = doPut(node.left, key, value);
  175. } else {
  176. //向右找,并建立父子关系
  177. node.right = doPut(node.right, key, value);
  178. }
  179. //更新节点高度
  180. updateHeight(node);
  181. //重新平衡树
  182. return checkBalance(node);
  183. }
  184. //删除
  185. public void remove(int key) {
  186. root = doRemove(root, key);
  187. }
  188. private AVLNode doRemove(AVLNode node, int key) {
  189. //1. node==null
  190. if (node == null) {
  191. return node;
  192. }
  193. //2.未找到key
  194. if (key < node.key) {
  195. //未找到key,且key小于当前节点key,继续向左
  196. node.left = doRemove(node.left, key);
  197. } else if (key > node.key) {
  198. //向右找
  199. node.right = doRemove(node.right, key);
  200. } else {
  201. //3.找到key
  202. if (node.left == null && node.right == null) {
  203. //3.1 没有子节点
  204. return null;
  205. } else if (node.left != null && node.right == null) {
  206. //3.2 一个子节点(左节点)
  207. node = node.left;
  208. } else if (node.left == null && node.right != null) {
  209. //3.2 一个子节点(右节点)
  210. node = node.right;
  211. } else {
  212. //3.3 两个子节点
  213. //找到他最小的后继节点,右子树向左找到底
  214. AVLNode s=node;
  215. while (s.left!=null){
  216. s=s.left;
  217. }
  218. //s即为后继节点,将节点删除并重新修正右子树
  219. s.right=doRemove(s.right,s.key);
  220. //左子树为s.left,右子树为原删除节点的左子树
  221. s.left=node.left;
  222. node=s;
  223. }
  224. }
  225. //4.更新高度
  226. updateHeight(node);
  227. //5.检查是否失衡
  228. return checkBalance(node);
  229. }
  230. }

11. 红黑树

红黑树也是一种自平衡的二叉搜索树,较之 AVL,插入和删除时旋转次数更少
红黑树特性
        1.所有节点都有两种颜色:红与黑
        2.所有 null 视为黑色
        3.红色节点不能相邻
        4.根节点是黑色
        5.从根到任意一个叶子节点,路径中的黑色节点数一样(黑色完美平衡)

补充:黑色叶子结点一般是成对出现,单独出现必定不平衡

11.1 node内部类

  1. private static class Node {
  2. int key;
  3. Object value;
  4. Node left;
  5. Node right;
  6. Node parent;//父节点
  7. Color color = RED;//颜色
  8. //是否是左孩子,左未true,右为false
  9. boolean isLeftChild() {
  10. return parent != null && this == parent.left;
  11. }
  12. //获取叔叔节点
  13. Node uncle() {
  14. //有父节点,和父节点的父节点才能有叔叔节点
  15. if (parent == null || parent.parent == null) {
  16. return null;
  17. }
  18. if (parent.isLeftChild()) {
  19. //如果父亲为左子节点则返回右子节点,
  20. return parent.parent.right;
  21. } else {
  22. //如果父亲为右子节点则返回左子节点
  23. return parent.parent.left;
  24. }
  25. }
  26. //获取兄弟节点
  27. Node sibling() {
  28. if(parent==null){
  29. return null;
  30. }
  31. if(this.isLeftChild()){
  32. return parent.right;
  33. }else {
  34. return parent.left;
  35. }
  36. }
  37. }

11.2 判断颜色

  1. //判断颜色
  2. boolean isRed(Node node){
  3. return node!=null&&node.color==RED;
  4. }
  5. boolean isBlack(Node node){
  6. return node==null||node.color==BLACK;
  7. }

11.3 左旋和右旋

  1. //和AVL树的不同
  2. // 右旋1.父(Parent)的处理2.旋转后新根的父子关系方法内处理
  3. void rotateRight(Node pink) {
  4. //获取pink的父级几点
  5. Node parent = pink.parent;
  6. //旋转
  7. Node yellow = pink.left;
  8. Node gree = yellow.right;
  9. //右旋之后换色节点的右子结点变为Pink
  10. yellow.right = pink;
  11. //之前黄色节点的左子结点赋值给pink,完成右旋
  12. pink.left = gree;
  13. if (gree != null) {
  14. //处理父子关系
  15. gree.parent = pink;
  16. }
  17. //处理父子关系
  18. yellow.parent = parent;
  19. pink.parent = yellow;
  20. //如果parent为空则根节点为yellow
  21. if (parent == null) {
  22. root = yellow;
  23. } else if (parent.left == pink) {
  24. //处理父子关系,yellow代替pink
  25. parent.left = yellow;
  26. } else {
  27. parent.right = yellow;
  28. }
  29. }
  30. void rotateLeft(Node pink) {
  31. //获取pink的父级几点
  32. Node parent = pink.parent;
  33. //旋转
  34. Node yellow = pink.right;
  35. Node gree = yellow.left;
  36. //右旋之后换色节点的右子结点变为Pink
  37. yellow.left = pink;
  38. //之前黄色节点的左子结点赋值给pink,完成右旋
  39. pink.right = gree;
  40. if (gree != null) {
  41. //处理父子关系
  42. gree.parent = pink;
  43. }
  44. //处理父子关系
  45. yellow.parent = parent;
  46. pink.parent = yellow;
  47. //如果parent为空则根节点为yellow
  48. if (parent == null) {
  49. root = yellow;
  50. } else if (parent.right == pink) {
  51. //处理父子关系,yellow代替pink
  52. parent.right = yellow;
  53. } else {
  54. parent.left = yellow;
  55. }
  56. }

11.4 新增或更新

  1. //新增或更新
  2. void put(int key, Object value) {
  3. Node p = root;
  4. Node parent = null;
  5. while (p != null) {
  6. parent = p;
  7. if (key < p.key) {
  8. //向左找
  9. p = p.left;
  10. } else if (key > p.key) {
  11. p = p.right;
  12. } else {
  13. //更新
  14. p.value = value;
  15. return;
  16. }
  17. }
  18. //插入
  19. Node interestNode = new Node(key, value);
  20. //如果parent为空
  21. if (parent == null) {
  22. root = interestNode;
  23. } else if (key < parent.key) {
  24. parent.left = interestNode;
  25. interestNode.parent = parent;
  26. } else {
  27. parent.right = interestNode;
  28. interestNode.parent = parent;
  29. }
  30. fixRedRed(interestNode);
  31. }
  32. /*
  33. * 1.所有节点都有两种颜色:红与黑
  34. * 2.所有 null 视为黑色
  35. * 3.红色节点不能相邻
  36. * 4.根节点是黑色
  37. * 5.从根到任意一个叶子节点,路径中的黑色节点数一样(黑色完美平衡)
  38. * */
  39. //修复红红不平衡
  40. void fixRedRed(Node x) {
  41. /*
  42. * 插入节点均视为红色
  43. * 插入节点的父亲为红色
  44. * 触发红红相邻
  45. * case 3:叔叔为红色
  46. * case 4:叔叔为黑色
  47. * */
  48. //case 1:插入节点为根节点,将根节点变黑
  49. if (x == root) {
  50. x.color = BLACK;
  51. return;
  52. }
  53. //case 2:插入节点的父亲若为黑色树的红黑性质不变,无需调整
  54. if (isBlack(x.parent)) {
  55. return;
  56. }
  57. Node parent = x.parent;
  58. Node uncle = x.uncle();
  59. Node grandParent = parent.parent;
  60. //插入节点的父亲为红色
  61. if (isRed(uncle)) {
  62. //红红相邻叔叔为红色时(仅通过变色即可)
  63. /*
  64. * 为了保证黑色平衡,连带的叔叔也变为黑色·
  65. * 祖父如果是黑色不变,会造成这颗子树黑色过多,因此祖父节点变为红色祖父如果变成红色,
  66. * 可能会接着触发红红相邻,因此对将祖父进行递归调整,祖父的父亲变为黑色
  67. * */
  68. parent.color = BLACK;
  69. uncle.color = BLACK;
  70. grandParent.color = RED;
  71. fixRedRed(grandParent);
  72. return;
  73. } else {
  74. //触发红红相邻叔叔为黑色
  75. /*
  76. * 1.父亲为左孩子,插入节点也是左孩子,此时即 LL不平衡(右旋一次)
  77. * 2.父亲为左孩子,插入节点是右孩子,此时即 LR不平衡(父亲左旋,祖父右旋)
  78. * 3.父亲为右孩子,插入节点也是右孩子,此时即 RR不平衡(左旋一次)
  79. * 4.父亲为右孩子,插入节点是左孩子,此时即 RL不平衡(父亲右旋,祖父左旋)
  80. *
  81. */
  82. if (parent.isLeftChild() && x.isLeftChild()) {
  83. //如果父亲为左子节点,查询节点也为左子结点即为LL(祖父右旋处理)
  84. //父节点变黑(和叔叔节点同为黑色)
  85. parent.color = BLACK;
  86. //祖父节点变红
  87. grandParent.color = RED;
  88. rotateRight(grandParent);
  89. } else if (parent.isLeftChild() && !x.isLeftChild()) {
  90. //parent为左子节点,插入节点为右子节点,LR(父亲左旋,祖父右旋)
  91. rotateLeft(parent);
  92. //插入节点变为黑色
  93. x.color=BLACK;
  94. //祖父变为红色
  95. grandParent.color=RED;
  96. rotateRight(grandParent);
  97. } else if (!parent.isLeftChild()&&!x.isLeftChild()) {
  98. //父节点变黑(和叔叔节点同为黑色)
  99. parent.color = BLACK;
  100. //祖父节点变红
  101. grandParent.color = RED;
  102. rotateLeft(grandParent);
  103. }else if(!parent.isLeftChild()&&x.isLeftChild()){
  104. rotateRight(parent);
  105. //插入节点变为黑色
  106. x.color=BLACK;
  107. //祖父变为红色
  108. grandParent.color=RED;
  109. rotateLeft(grandParent);
  110. }
  111. }
  112. }

11.5 删除

  1. //删除
  2. /*
  3. * 删除
  4. * 正常删、会用到李代桃僵技巧、遇到黑黑不平衡进行调整
  5. * */
  6. public void remove(int key) {
  7. Node deleted = find(key);
  8. if (deleted == null) {
  9. return;
  10. }
  11. doRemove(deleted);
  12. }
  13. //检测双黑节点删除
  14. /*
  15. *
  16. * 删除节点和剩下节点都是黑触发双黑,双黑意思是,少了一个黑
  17. * case 3:删除节点或剩余节点的兄弟为红此时两个侄子定为黑
  18. * case 4:删除节点或剩余节点的兄弟、和兄弟孩子都为黑
  19. * case 5:删除节点的兄弟为黑,至少一个红侄子
  20. *
  21. * */
  22. private void fixDoubleBlack(Node x) {
  23. //把case3处理为case4和case5
  24. if (x == root) {
  25. return;
  26. }
  27. Node parent = x.parent;
  28. Node sibling = x.sibling();
  29. if (sibling.color == RED) {
  30. //进入case3
  31. if (x.isLeftChild()) {
  32. //如果是做孩子就进行左旋
  33. rotateLeft(parent);
  34. } else {
  35. //如果是右孩子就进行右旋
  36. rotateRight(parent);
  37. }
  38. //父亲颜色变为红色(父亲变色前肯定为黑色)
  39. parent.color = RED;
  40. //兄弟变为黑色
  41. sibling.color = BLACK;
  42. //此时case3 已经被转换为 case4或者case5
  43. fixDoubleBlack(x);
  44. return;
  45. }
  46. //兄弟为黑
  47. //两个侄子都为黑
  48. if (sibling != null) {
  49. if (isBlack(sibling.left) && isBlack(sibling.right)) {
  50. /*
  51. * case 4:被调整节点的兄弟为黑,两个侄于都为黑
  52. * 将兄弟变红, 目的是将删除节点和兄弟那边的黑色高度同时减少1
  53. * 如果父亲是红,则需将父亲变为黑,避免红红,此时路径黑节点数目不变
  54. * 如果父亲是黑,说明这条路径则少了一个黑,再次让父节点触发双黑
  55. * */
  56. //将兄弟变红, 目的是将删除节点和兄弟那边的黑色高度同时减少1
  57. sibling.color = RED;
  58. if (isRed(parent)) {
  59. // 如果父亲是红,则需将父亲变为黑,避免红红,此时路径黑节点数目不变
  60. parent.color = BLACK;
  61. } else {
  62. //如果父亲是黑,说明这条路径则少了一个黑,再次让父节点触发双黑
  63. fixDoubleBlack(parent);
  64. }
  65. } else {
  66. //CASE5 至少有一个侄子不是黑色
  67. /*
  68. *
  69. * case 5:被调整节点的兄弟为黑
  70. * 如果兄弟是左孩子,左侄子是红 LL 不平衡
  71. * 如果兄弟是左孩子,右侄子是红 LR 不平衡
  72. * 如果兄弟是右孩子,右侄于是红 RR 不平衡
  73. * 如果兄弟是右孩子,左侄于是红 RL 不平衡
  74. * */
  75. if(sibling.isLeftChild()&&isRed(sibling.left)){
  76. // 如果兄弟是左孩子,左侄子是红 LL 不平衡
  77. rotateRight(parent);
  78. //兄弟的做孩子变黑
  79. sibling.left.color=BLACK;
  80. //兄弟变成父亲的颜色
  81. sibling.color= parent.color;
  82. //父亲变黑
  83. parent.color=BLACK;
  84. }else if(sibling.isLeftChild()&&isRed(sibling.right)){
  85. //如果兄弟是左孩子,右侄子是红 LR 不平衡
  86. //变色必须在上 否则旋转后会空指针
  87. //兄弟的右孩子变为父节点颜色
  88. sibling.right.color= parent.color;
  89. //父节点变黑
  90. parent.color=BLACK;
  91. rotateLeft(sibling);
  92. rotateRight(parent);
  93. }
  94. }
  95. } else {
  96. fixDoubleBlack(parent);
  97. }
  98. }
  99. private void doRemove(Node deleted) {
  100. Node replaced = findReplaced(deleted);
  101. Node parent = deleted.parent;
  102. if (replaced == null) {
  103. //没有子节点
  104. /* case1:删的是根节点,没有子节点
  105. * 删完了,直接将 root=null
  106. * */
  107. if (deleted == root) {
  108. root = null;
  109. } else {
  110. /*
  111. * Case2:删的是黑,剩下的是红剩下这个红节点变黑
  112. * */
  113. if (isBlack(deleted)) {
  114. //复杂处理,先调整平衡再删除
  115. fixDoubleBlack(deleted);
  116. } else {
  117. //红色不处理
  118. }
  119. //删除的不是根节点且没有孩子
  120. if (deleted.isLeftChild()) {
  121. parent.left = null;
  122. } else {
  123. parent.right = null;
  124. }
  125. deleted.parent = null;
  126. }
  127. return;
  128. } else if (replaced.left == null || replaced.right == null) {
  129. //有一个子节点
  130. /* case1:删的是根节点,有一个子节点
  131. * 用剩余节点替换了根节点的 key,Value,根节点孩子=null,颜色保持黑色 不变
  132. * */
  133. if (deleted == root) {
  134. root.key = replaced.key;
  135. root.value = replaced.value;
  136. root.left = root.right = null;
  137. } else {
  138. //删除的不是根节点但是有一个孩子
  139. if (deleted.isLeftChild()) {
  140. parent.left = replaced;
  141. } else {
  142. parent.right = replaced;
  143. }
  144. replaced.parent = parent;
  145. deleted.right = deleted.left = deleted.parent = null;
  146. if (isBlack(deleted) && isBlack(replaced)) {
  147. //如果删除的是黑色剩下的也是黑色,需要复杂处理,先删除再平衡
  148. fixDoubleBlack(replaced);
  149. } else {
  150. /*
  151. * Case2:删的是黑,剩下的是红剩下这个红节点变黑
  152. * */
  153. replaced.color = BLACK;
  154. }
  155. }
  156. return;
  157. } else {
  158. //两个子节点
  159. //交换删除节点和删除节点的后几点的key,value,这
  160. // 样被删除节点就只有一个子节点或没有子节点了
  161. int t = deleted.key;
  162. deleted.key = replaced.key;
  163. replaced.key = t;
  164. Object v = deleted.value;
  165. deleted.value = replaced.value;
  166. replaced.value = v;
  167. doRemove(replaced);
  168. return;
  169. }
  170. }
  171. private Node find(int key) {
  172. Node p = root;
  173. while (p != null) {
  174. if (key > p.key) {
  175. //key更大向右找
  176. p = p.right;
  177. } else if (key < p.key) {
  178. //向左找
  179. p = p.left;
  180. } else {
  181. return p;
  182. }
  183. }
  184. return null;
  185. }
  186. //查找删除后的剩余节点
  187. private Node findReplaced(Node deleted) {
  188. if (deleted.left == null & deleted.right == null) {
  189. //没有子节点
  190. return null;
  191. } else if (deleted.left == null) {
  192. return deleted.right;
  193. } else if (deleted.right == null) {
  194. return deleted.left;
  195. } else {
  196. Node s = deleted.right;
  197. while (s != null) {
  198. //右子树的最小值
  199. s = s.left;
  200. }
  201. return s;
  202. }
  203. }
  204. }

 11.6 完整代码

  1. package org.alogorithm.tree;
  2. import static org.alogorithm.tree.RedBlackTree.Color.BLACK;
  3. import static org.alogorithm.tree.RedBlackTree.Color.RED;
  4. public class RedBlackTree {
  5. enum Color {RED, BLACK}
  6. private Node root;
  7. private static class Node {
  8. int key;
  9. Object value;
  10. Node left;
  11. Node right;
  12. Node parent;//父节点
  13. Color color = RED;//颜色
  14. public Node() {
  15. }
  16. public Node(int key, Object value) {
  17. this.key = key;
  18. this.value = value;
  19. }
  20. //是否是左孩子,左未true,右为false
  21. boolean isLeftChild() {
  22. return parent != null && this == parent.left;
  23. }
  24. //获取叔叔节点
  25. Node uncle() {
  26. //有父节点,和父节点的父节点才能有叔叔节点
  27. if (parent == null || parent.parent == null) {
  28. return null;
  29. }
  30. if (parent.isLeftChild()) {
  31. //如果父亲为左子节点则返回右子节点,
  32. return parent.parent.right;
  33. } else {
  34. //如果父亲为右子节点则返回左子节点
  35. return parent.parent.left;
  36. }
  37. }
  38. //获取兄弟节点
  39. Node sibling() {
  40. if (parent == null) {
  41. return null;
  42. }
  43. if (this.isLeftChild()) {
  44. return parent.right;
  45. } else {
  46. return parent.left;
  47. }
  48. }
  49. }
  50. //判断颜色
  51. boolean isRed(Node node) {
  52. return node != null && node.color == RED;
  53. }
  54. boolean isBlack(Node node) {
  55. return node == null || node.color == BLACK;
  56. }
  57. //和AVL树的不同
  58. // 右旋1.父(Parent)的处理2.旋转后新根的父子关系方法内处理
  59. void rotateRight(Node pink) {
  60. //获取pink的父级几点
  61. Node parent = pink.parent;
  62. //旋转
  63. Node yellow = pink.left;
  64. Node gree = yellow.right;
  65. //右旋之后换色节点的右子结点变为Pink
  66. yellow.right = pink;
  67. //之前黄色节点的左子结点赋值给pink,完成右旋
  68. pink.left = gree;
  69. if (gree != null) {
  70. //处理父子关系
  71. gree.parent = pink;
  72. }
  73. //处理父子关系
  74. yellow.parent = parent;
  75. pink.parent = yellow;
  76. //如果parent为空则根节点为yellow
  77. if (parent == null) {
  78. root = yellow;
  79. } else if (parent.left == pink) {
  80. //处理父子关系,yellow代替pink
  81. parent.left = yellow;
  82. } else {
  83. parent.right = yellow;
  84. }
  85. }
  86. void rotateLeft(Node pink) {
  87. //获取pink的父级几点
  88. Node parent = pink.parent;
  89. //旋转
  90. Node yellow = pink.right;
  91. Node gree = yellow.left;
  92. //右旋之后换色节点的右子结点变为Pink
  93. yellow.left = pink;
  94. //之前黄色节点的左子结点赋值给pink,完成右旋
  95. pink.right = gree;
  96. if (gree != null) {
  97. //处理父子关系
  98. gree.parent = pink;
  99. }
  100. //处理父子关系
  101. yellow.parent = parent;
  102. pink.parent = yellow;
  103. //如果parent为空则根节点为yellow
  104. if (parent == null) {
  105. root = yellow;
  106. } else if (parent.right == pink) {
  107. //处理父子关系,yellow代替pink
  108. parent.right = yellow;
  109. } else {
  110. parent.left = yellow;
  111. }
  112. }
  113. //新增或更新
  114. void put(int key, Object value) {
  115. Node p = root;
  116. Node parent = null;
  117. while (p != null) {
  118. parent = p;
  119. if (key < p.key) {
  120. //向左找
  121. p = p.left;
  122. } else if (key > p.key) {
  123. p = p.right;
  124. } else {
  125. //更新
  126. p.value = value;
  127. return;
  128. }
  129. }
  130. //插入
  131. Node interestNode = new Node(key, value);
  132. //如果parent为空
  133. if (parent == null) {
  134. root = interestNode;
  135. } else if (key < parent.key) {
  136. parent.left = interestNode;
  137. interestNode.parent = parent;
  138. } else {
  139. parent.right = interestNode;
  140. interestNode.parent = parent;
  141. }
  142. fixRedRed(interestNode);
  143. }
  144. /*
  145. * 1.所有节点都有两种颜色:红与黑
  146. * 2.所有 null 视为黑色
  147. * 3.红色节点不能相邻
  148. * 4.根节点是黑色
  149. * 5.从根到任意一个叶子节点,路径中的黑色节点数一样(黑色完美平衡)
  150. * */
  151. //修复红红不平衡
  152. void fixRedRed(Node x) {
  153. /*
  154. * 插入节点均视为红色
  155. * 插入节点的父亲为红色
  156. * 触发红红相邻
  157. * case 3:叔叔为红色
  158. * case 4:叔叔为黑色
  159. * */
  160. //case 1:插入节点为根节点,将根节点变黑
  161. if (x == root) {
  162. x.color = BLACK;
  163. return;
  164. }
  165. //case 2:插入节点的父亲若为黑色树的红黑性质不变,无需调整
  166. if (isBlack(x.parent)) {
  167. return;
  168. }
  169. Node parent = x.parent;
  170. Node uncle = x.uncle();
  171. Node grandParent = parent.parent;
  172. //插入节点的父亲为红色
  173. if (isRed(uncle)) {
  174. //红红相邻叔叔为红色时(仅通过变色即可)
  175. /*
  176. * 为了保证黑色平衡,连带的叔叔也变为黑色·
  177. * 祖父如果是黑色不变,会造成这颗子树黑色过多,因此祖父节点变为红色祖父如果变成红色,
  178. * 可能会接着触发红红相邻,因此对将祖父进行递归调整,祖父的父亲变为黑色
  179. * */
  180. parent.color = BLACK;
  181. uncle.color = BLACK;
  182. grandParent.color = RED;
  183. fixRedRed(grandParent);
  184. return;
  185. } else {
  186. //触发红红相邻叔叔为黑色
  187. /*
  188. * 1.父亲为左孩子,插入节点也是左孩子,此时即 LL不平衡(右旋一次)
  189. * 2.父亲为左孩子,插入节点是右孩子,此时即 LR不平衡(父亲左旋,祖父右旋)
  190. * 3.父亲为右孩子,插入节点也是右孩子,此时即 RR不平衡(左旋一次)
  191. * 4.父亲为右孩子,插入节点是左孩子,此时即 RL不平衡(父亲右旋,祖父左旋)
  192. *
  193. */
  194. if (parent.isLeftChild() && x.isLeftChild()) {
  195. //如果父亲为左子节点,查询节点也为左子结点即为LL(祖父右旋处理)
  196. //父节点变黑(和叔叔节点同为黑色)
  197. parent.color = BLACK;
  198. //祖父节点变红
  199. grandParent.color = RED;
  200. rotateRight(grandParent);
  201. } else if (parent.isLeftChild() && !x.isLeftChild()) {
  202. //parent为左子节点,插入节点为右子节点,LR(父亲左旋,祖父右旋)
  203. rotateLeft(parent);
  204. //插入节点变为黑色
  205. x.color = BLACK;
  206. //祖父变为红色
  207. grandParent.color = RED;
  208. rotateRight(grandParent);
  209. } else if (!parent.isLeftChild() && !x.isLeftChild()) {
  210. //父节点变黑(和叔叔节点同为黑色)
  211. parent.color = BLACK;
  212. //祖父节点变红
  213. grandParent.color = RED;
  214. rotateLeft(grandParent);
  215. } else if (!parent.isLeftChild() && x.isLeftChild()) {
  216. rotateRight(parent);
  217. //插入节点变为黑色
  218. x.color = BLACK;
  219. //祖父变为红色
  220. grandParent.color = RED;
  221. rotateLeft(grandParent);
  222. }
  223. }
  224. }
  225. //删除
  226. /*
  227. * 删除
  228. * 正常删、会用到李代桃僵技巧、遇到黑黑不平衡进行调整
  229. * */
  230. public void remove(int key) {
  231. Node deleted = find(key);
  232. if (deleted == null) {
  233. return;
  234. }
  235. doRemove(deleted);
  236. }
  237. //检测双黑节点删除
  238. /*
  239. *
  240. * 删除节点和剩下节点都是黑触发双黑,双黑意思是,少了一个黑
  241. * case 3:删除节点或剩余节点的兄弟为红此时两个侄子定为黑
  242. * case 4:删除节点或剩余节点的兄弟、和兄弟孩子都为黑
  243. * case 5:删除节点的兄弟为黑,至少一个红侄子
  244. *
  245. * */
  246. private void fixDoubleBlack(Node x) {
  247. //把case3处理为case4和case5
  248. if (x == root) {
  249. return;
  250. }
  251. Node parent = x.parent;
  252. Node sibling = x.sibling();
  253. if (sibling.color == RED) {
  254. //进入case3
  255. if (x.isLeftChild()) {
  256. //如果是做孩子就进行左旋
  257. rotateLeft(parent);
  258. } else {
  259. //如果是右孩子就进行右旋
  260. rotateRight(parent);
  261. }
  262. //父亲颜色变为红色(父亲变色前肯定为黑色)
  263. parent.color = RED;
  264. //兄弟变为黑色
  265. sibling.color = BLACK;
  266. //此时case3 已经被转换为 case4或者case5
  267. fixDoubleBlack(x);
  268. return;
  269. }
  270. //兄弟为黑
  271. //两个侄子都为黑
  272. if (sibling != null) {
  273. if (isBlack(sibling.left) && isBlack(sibling.right)) {
  274. /*
  275. * case 4:被调整节点的兄弟为黑,两个侄于都为黑
  276. * 将兄弟变红, 目的是将删除节点和兄弟那边的黑色高度同时减少1
  277. * 如果父亲是红,则需将父亲变为黑,避免红红,此时路径黑节点数目不变
  278. * 如果父亲是黑,说明这条路径则少了一个黑,再次让父节点触发双黑
  279. * */
  280. //将兄弟变红, 目的是将删除节点和兄弟那边的黑色高度同时减少1
  281. sibling.color = RED;
  282. if (isRed(parent)) {
  283. // 如果父亲是红,则需将父亲变为黑,避免红红,此时路径黑节点数目不变
  284. parent.color = BLACK;
  285. } else {
  286. //如果父亲是黑,说明这条路径则少了一个黑,再次让父节点触发双黑
  287. fixDoubleBlack(parent);
  288. }
  289. } else {
  290. //CASE5 至少有一个侄子不是黑色
  291. /*
  292. *
  293. * case 5:被调整节点的兄弟为黑
  294. * 如果兄弟是左孩子,左侄子是红 LL 不平衡
  295. * 如果兄弟是左孩子,右侄子是红 LR 不平衡
  296. * 如果兄弟是右孩子,右侄于是红 RR 不平衡
  297. * 如果兄弟是右孩子,左侄于是红 RL 不平衡
  298. * */
  299. if(sibling.isLeftChild()&&isRed(sibling.left)){
  300. // 如果兄弟是左孩子,左侄子是红 LL 不平衡
  301. rotateRight(parent);
  302. //兄弟的做孩子变黑
  303. sibling.left.color=BLACK;
  304. //兄弟变成父亲的颜色
  305. sibling.color= parent.color;
  306. //父亲变黑
  307. parent.color=BLACK;
  308. }else if(sibling.isLeftChild()&&isRed(sibling.right)){
  309. //如果兄弟是左孩子,右侄子是红 LR 不平衡
  310. //变色必须在上 否则旋转后会空指针
  311. //兄弟的右孩子变为父节点颜色
  312. sibling.right.color= parent.color;
  313. //父节点变黑
  314. parent.color=BLACK;
  315. rotateLeft(sibling);
  316. rotateRight(parent);
  317. }
  318. }
  319. } else {
  320. fixDoubleBlack(parent);
  321. }
  322. }
  323. private void doRemove(Node deleted) {
  324. Node replaced = findReplaced(deleted);
  325. Node parent = deleted.parent;
  326. if (replaced == null) {
  327. //没有子节点
  328. /* case1:删的是根节点,没有子节点
  329. * 删完了,直接将 root=null
  330. * */
  331. if (deleted == root) {
  332. root = null;
  333. } else {
  334. /*
  335. * Case2:删的是黑,剩下的是红剩下这个红节点变黑
  336. * */
  337. if (isBlack(deleted)) {
  338. //复杂处理,先调整平衡再删除
  339. fixDoubleBlack(deleted);
  340. } else {
  341. //红色不处理
  342. }
  343. //删除的不是根节点且没有孩子
  344. if (deleted.isLeftChild()) {
  345. parent.left = null;
  346. } else {
  347. parent.right = null;
  348. }
  349. deleted.parent = null;
  350. }
  351. return;
  352. } else if (replaced.left == null || replaced.right == null) {
  353. //有一个子节点
  354. /* case1:删的是根节点,有一个子节点
  355. * 用剩余节点替换了根节点的 key,Value,根节点孩子=null,颜色保持黑色 不变
  356. * */
  357. if (deleted == root) {
  358. root.key = replaced.key;
  359. root.value = replaced.value;
  360. root.left = root.right = null;
  361. } else {
  362. //删除的不是根节点但是有一个孩子
  363. if (deleted.isLeftChild()) {
  364. parent.left = replaced;
  365. } else {
  366. parent.right = replaced;
  367. }
  368. replaced.parent = parent;
  369. deleted.right = deleted.left = deleted.parent = null;
  370. if (isBlack(deleted) && isBlack(replaced)) {
  371. //如果删除的是黑色剩下的也是黑色,需要复杂处理,先删除再平衡
  372. fixDoubleBlack(replaced);
  373. } else {
  374. /*
  375. * Case2:删的是黑,剩下的是红剩下这个红节点变黑
  376. * */
  377. replaced.color = BLACK;
  378. }
  379. }
  380. return;
  381. } else {
  382. //两个子节点
  383. //交换删除节点和删除节点的后几点的key,value,这
  384. // 样被删除节点就只有一个子节点或没有子节点了
  385. int t = deleted.key;
  386. deleted.key = replaced.key;
  387. replaced.key = t;
  388. Object v = deleted.value;
  389. deleted.value = replaced.value;
  390. replaced.value = v;
  391. doRemove(replaced);
  392. return;
  393. }
  394. }
  395. private Node find(int key) {
  396. Node p = root;
  397. while (p != null) {
  398. if (key > p.key) {
  399. //key更大向右找
  400. p = p.right;
  401. } else if (key < p.key) {
  402. //向左找
  403. p = p.left;
  404. } else {
  405. return p;
  406. }
  407. }
  408. return null;
  409. }
  410. //查找删除后的剩余节点
  411. private Node findReplaced(Node deleted) {
  412. if (deleted.left == null & deleted.right == null) {
  413. //没有子节点
  414. return null;
  415. } else if (deleted.left == null) {
  416. return deleted.right;
  417. } else if (deleted.right == null) {
  418. return deleted.left;
  419. } else {
  420. Node s = deleted.right;
  421. while (s != null) {
  422. //右子树的最小值
  423. s = s.left;
  424. }
  425. return s;
  426. }
  427. }
  428. }

 10.AVL树

AVL 树(平衡二叉搜索树)
        二叉搜索树在插入和删除时,节点可能失衡
        如果在插入和删除时通过旋转,始终让二叉搜索树保持平衡,称为自平衡的二叉搜索树
        AVL是自平衡二又搜索树的实现之一

        如果一个节点的左右孩子,高度差超过1,则此节点失衡,才需要旋转。

10.1 获取高度

  1. //处理节点高度
  2. private int haight(AVLNode node) {
  3. return node == null ? 0 : node.height;
  4. }

10.2更新高度

  1. //增、删、旋转更新节点高度
  2. //最大高度+1
  3. public void updateHeight(AVLNode treeNode) {
  4. treeNode.height=Integer.max(haight(treeNode.left),haight(treeNode.right))+1;
  5. }

10.1 旋转

10.1.1 平衡因子

平衡因子:一个节点左子树高度-右子树高度所得结果
 小于1平衡:(0,1,-1)
 大于1不平衡
       >1:左边高
       <-1:右边高

        

  1. public int bf(AVLNode avlNode){
  2. return haight(avlNode.left)-haight(avlNode.right);
  3. }

10.1.2 四种失衡情况

 LL
    -失衡节点的 bf >1,即左边更高
    -失衡节点的左孩子的bf>=0即左孩子这边也是左边更高或等
    一次右旋可以恢复平衡
 LR
    -失衡节点的 bf >1,即左边更高
    -失衡节点的左孩子的bf<0 即左孩子这边是右边更高
    左子节点先左旋,将树修正为LL情况,
    然后失衡节点再右旋,恢复平衡
RL
    -失衡节点的 bf <-1,即右边更高
    -失衡节点的右孩子的bf>0,即右孩子这边左边更高
    右子节点先右旋,将树修正为RR情况,
    然后失衡节点再左旋,恢复平衡
 RR
    -失衡节点的 bf<-1,即右边更高
    -失衡节点的右孩子的bf<=0,即右孩子这边右边更高或等高
    一次左旋可以恢复平衡
  1. //右旋
  2. /**
  3. * @Description 返回旋转后的节点
  4. * @Param [avlNode] 需要旋转的节点
  5. **/
  6. private AVLNode rightRotate(AVLNode redNode) {
  7. AVLNode yellowNode = redNode.left;
  8. /*
  9. *黄色节点有右子节点,给右子节点重新找父级节点
  10. *由于二叉搜索树特性,某个节点的左子节点必定小于 本身,右子节点必定大于本身
  11. * 故:yelllow的右子节点必定大于yellow且小于rea,
  12. * 所以,gree可以作为red的左子结点
  13. * */
  14. /*
  15. AVLNode greeNode = yellowNode.right;
  16. redNode.left = greeNode;
  17. */
  18. redNode.left = yellowNode.right;
  19. yellowNode.right = redNode;
  20. //更新高度,红色和黄色都会改变
  21. updateHeight(redNode);
  22. updateHeight(yellowNode);
  23. return yellowNode;
  24. }
  25. //左旋
  26. private AVLNode leftRotate(AVLNode redNode) {
  27. //左旋和右旋操作相反
  28. AVLNode yellowNode = redNode.right;
  29. //处理yellow的子节点
  30. redNode.right = yellowNode.left;
  31. //yellow变为跟,原red比yellow小,为yellow的left
  32. yellowNode.left=redNode;
  33. updateHeight(redNode);
  34. updateHeight(yellowNode);
  35. return yellowNode;
  36. }
  37. /*
  38. * LR
  39. -失衡节点的 bf >1,即左边更高
  40. -失衡节点的左孩子的bf<0 即左孩子这边是右边更高
  41. 左子节点先左旋,将树修正为LL情况,
  42. 然后失衡节点再右旋,恢复平衡
  43. * */
  44. //先左旋再右旋
  45. private AVLNode leftRightRotate(AVLNode node) {
  46. //修正左子结点LL
  47. node.left = leftRotate(node.left);
  48. return rightRotate(node);
  49. }
  50. /*
  51. * RL
  52. -失衡节点的 bf <-1,即右边更高
  53. -失衡节点的右孩子的bf>0,即右孩子这边左边更高
  54. 右子节点先右旋,将树修正为RR情况,
  55. 然后失衡节点再左旋,恢复平衡
  56. * */
  57. //先右旋再左旋
  58. private AVLNode rightLeftRotate(AVLNode node) {
  59. //修正右子节点为RR
  60. node.right= rightRotate(node.left);
  61. return leftRotate(node);
  62. }

10.1.3 返回一个平衡后的树

  1. //检查节点是否失衡,重新平衡
  2. private AVLNode checkBalance(AVLNode node) {
  3. if (node == null) {
  4. return null;
  5. }
  6. //获取该节点的平衡因子
  7. int bf = bf(node);
  8. if (bf > 1) {
  9. //左边更高的两种情况根据 左子树平衡因子判定
  10. int leftBf = bf(node.left);
  11. if (leftBf >= 0) {
  12. //左子树左边高 LL 右旋 考虑到删除时等于0也应该右旋
  13. return rightRotate(node);
  14. } else {
  15. //左子树右边更高 LR
  16. return leftRightRotate(node);
  17. }
  18. } else if (bf < -1) {
  19. int rightBf = bf(node.right);
  20. if (rightBf <= 0) {
  21. //右子树左边更高 RR 虑到删除时等于0也要左旋
  22. return leftRotate(node);
  23. } else {
  24. //右子树右边更高 RL
  25. return rightLeftRotate(node);
  26. }
  27. }
  28. return node;
  29. }

10.2 新增

  1. public void put(int key, Object value){
  2. doPut(root,key,value);
  3. }
  4. //找空位并添加新的节点
  5. private AVLNode doPut(AVLNode node, int key, Object value) {
  6. /*
  7. * 1.找到空位,创建新节点
  8. * 2.key 已存在 更新位置
  9. * 3.继续寻找
  10. * */
  11. //未找到
  12. if (node ==null){
  13. return new AVLNode(key,value);
  14. }
  15. //找到了节点 重新赋值
  16. if(key ==node.key){
  17. node.value=value;
  18. return node;
  19. }
  20. //继续查找
  21. if(key < node.key){
  22. //继续向左,并建立父子关系
  23. node.left= doPut(node.left,key,value);
  24. }else{
  25. //向右找,并建立父子关系
  26. node.right= doPut(node.right,key,value);
  27. }
  28. //更新节点高度
  29. updateHeight(node);
  30. //重新平衡树
  31. return checkBalance(node);
  32. }

10.3 删除

  1. //删除
  2. public void remove(int key) {
  3. root = doRemove(root, key);
  4. }
  5. private AVLNode doRemove(AVLNode node, int key) {
  6. //1. node==null
  7. if (node == null) {
  8. return node;
  9. }
  10. //2.未找到key
  11. if (key < node.key) {
  12. //未找到key,且key小于当前节点key,继续向左
  13. node.left = doRemove(node.left, key);
  14. } else if (key > node.key) {
  15. //向右找
  16. node.right = doRemove(node.right, key);
  17. } else {
  18. //3.找到key
  19. if (node.left == null && node.right == null) {
  20. //3.1 没有子节点
  21. return null;
  22. } else if (node.left != null && node.right == null) {
  23. //3.2 一个子节点(左节点)
  24. node = node.left;
  25. } else if (node.left == null && node.right != null) {
  26. //3.2 一个子节点(右节点)
  27. node = node.right;
  28. } else {
  29. //3.3 两个子节点
  30. //找到他最小的后继节点,右子树向左找到底
  31. AVLNode s=node;
  32. while (s.left!=null){
  33. s=s.left;
  34. }
  35. //s即为后继节点,将节点删除并重新修正右子树
  36. s.right=doRemove(s.right,s.key);
  37. //左子树为s.left,右子树为原删除节点的左子树
  38. s.left=node.left;
  39. node=s;
  40. }
  41. }
  42. //4.更新高度
  43. updateHeight(node);
  44. //5.检查是否失衡
  45. return checkBalance(node);
  46. }

10.4 整体代码

  1. package org.alogorithm.tree.AVLTree;
  2. public class AVLTree {
  3. static class AVLNode {
  4. int key;
  5. int height = 1;//高度初始值1
  6. AVLNode left, right;
  7. private AVLNode root;
  8. Object value;
  9. public AVLNode(int key, Object value) {
  10. this.key = key;
  11. this.value = value;
  12. }
  13. public AVLNode(int key, AVLNode left, AVLNode right, AVLNode root) {
  14. this.key = key;
  15. this.left = left;
  16. this.right = right;
  17. this.root = root;
  18. }
  19. }
  20. //处理节点高度
  21. private int haight(AVLNode node) {
  22. return node == null ? 0 : node.height;
  23. }
  24. //增、删、旋转更新节点高度
  25. //最大高度+1
  26. public void updateHeight(AVLNode treeNode) {
  27. treeNode.height = Integer.max(haight(treeNode.left), haight(treeNode.right)) + 1;
  28. }
  29. /*
  30. 平衡因子:一个节点左子树高度-右子树高度所得结果
  31. 小于1平衡:(0,1,-1)
  32. 大于1不平衡
  33. >1:左边高
  34. <-1:右边高
  35. */
  36. public int bf(AVLNode avlNode) {
  37. return haight(avlNode.left) - haight(avlNode.right);
  38. }
  39. //四种失衡情况
  40. /*
  41. LL
  42. -失衡节点的 bf >1,即左边更高
  43. -失衡节点的左孩子的bf>=0即左孩子这边也是左边更高或等
  44. 一次右旋可以恢复平衡
  45. LR
  46. -失衡节点的 bf >1,即左边更高
  47. -失衡节点的左孩子的bf<0 即左孩子这边是右边更高
  48. 左子节点先左旋,将树修正为LL情况,
  49. 然后失衡节点再右旋,恢复平衡
  50. RL
  51. -失衡节点的 bf <-1,即右边更高
  52. -失衡节点的右孩子的bf>0,即右孩子这边左边更高
  53. 右子节点先右旋,将树修正为RR情况,
  54. 然后失衡节点再左旋,恢复平衡
  55. RR
  56. -失衡节点的 bf<-1,即右边更高
  57. -失衡节点的右孩子的bf<=0,即右孩子这边右边更高或等高
  58. 一次左旋可以恢复平衡
  59. */
  60. //右旋
  61. /**
  62. * @Description 返回旋转后的节点
  63. * @Param [avlNode] 需要旋转的节点
  64. **/
  65. private AVLNode rightRotate(AVLNode redNode) {
  66. AVLNode yellowNode = redNode.left;
  67. /*
  68. *黄色节点有右子节点,给右子节点重新找父级节点
  69. *由于二叉搜索树特性,某个节点的左子节点必定小于 本身,右子节点必定大于本身
  70. * 故:yelllow的右子节点必定大于yellow且小于rea,
  71. * 所以,gree可以作为red的左子结点
  72. * */
  73. /*
  74. AVLNode greeNode = yellowNode.right;
  75. redNode.left = greeNode;
  76. */
  77. redNode.left = yellowNode.right;
  78. yellowNode.right = redNode;
  79. //更新高度,红色和黄色都会改变
  80. updateHeight(redNode);
  81. updateHeight(yellowNode);
  82. return yellowNode;
  83. }
  84. //左旋
  85. private AVLNode leftRotate(AVLNode redNode) {
  86. //左旋和右旋操作相反
  87. AVLNode yellowNode = redNode.right;
  88. //处理yellow的子节点
  89. redNode.right = yellowNode.left;
  90. //yellow变为跟,原red比yellow小,为yellow的left
  91. yellowNode.left = redNode;
  92. updateHeight(redNode);
  93. updateHeight(yellowNode);
  94. return yellowNode;
  95. }
  96. /*
  97. * LR
  98. -失衡节点的 bf >1,即左边更高
  99. -失衡节点的左孩子的bf<0 即左孩子这边是右边更高
  100. 左子节点先左旋,将树修正为LL情况,
  101. 然后失衡节点再右旋,恢复平衡
  102. * */
  103. //先左旋再右旋
  104. private AVLNode leftRightRotate(AVLNode node) {
  105. //修正左子结点LL
  106. node.left = leftRotate(node.left);
  107. return rightRotate(node);
  108. }
  109. /*
  110. * RL
  111. -失衡节点的 bf <-1,即右边更高
  112. -失衡节点的右孩子的bf>0,即右孩子这边左边更高
  113. 右子节点先右旋,将树修正为RR情况,
  114. 然后失衡节点再左旋,恢复平衡
  115. * */
  116. //先右旋再左旋
  117. private AVLNode rightLeftRotate(AVLNode node) {
  118. //修正右子节点为RR
  119. node.right = rightRotate(node.left);
  120. return leftRotate(node);
  121. }
  122. //检查节点是否失衡,重新平衡
  123. private AVLNode checkBalance(AVLNode node) {
  124. if (node == null) {
  125. return null;
  126. }
  127. //获取该节点的平衡因子
  128. int bf = bf(node);
  129. if (bf > 1) {
  130. //左边更高的两种情况根据 左子树平衡因子判定
  131. int leftBf = bf(node.left);
  132. if (leftBf >= 0) {
  133. //左子树左边高 LL 右旋 考虑到删除时等于0也应该右旋
  134. return rightRotate(node);
  135. } else {
  136. //左子树右边更高 LR
  137. return leftRightRotate(node);
  138. }
  139. } else if (bf < -1) {
  140. int rightBf = bf(node.right);
  141. if (rightBf <= 0) {
  142. //右子树左边更高 RR 虑到删除时等于0也要左旋
  143. return leftRotate(node);
  144. } else {
  145. //右子树右边更高 RL
  146. return rightLeftRotate(node);
  147. }
  148. }
  149. return node;
  150. }
  151. AVLNode root;
  152. public void put(int key, Object value) {
  153. doPut(root, key, value);
  154. }
  155. //找空位并添加新的节点
  156. private AVLNode doPut(AVLNode node, int key, Object value) {
  157. /*
  158. * 1.找到空位,创建新节点
  159. * 2.key 已存在 更新位置
  160. * 3.继续寻找
  161. * */
  162. //未找到
  163. if (node == null) {
  164. return new AVLNode(key, value);
  165. }
  166. //找到了节点 重新赋值
  167. if (key == node.key) {
  168. node.value = value;
  169. return node;
  170. }
  171. //继续查找
  172. if (key < node.key) {
  173. //继续向左,并建立父子关系
  174. node.left = doPut(node.left, key, value);
  175. } else {
  176. //向右找,并建立父子关系
  177. node.right = doPut(node.right, key, value);
  178. }
  179. //更新节点高度
  180. updateHeight(node);
  181. //重新平衡树
  182. return checkBalance(node);
  183. }
  184. //删除
  185. public void remove(int key) {
  186. root = doRemove(root, key);
  187. }
  188. private AVLNode doRemove(AVLNode node, int key) {
  189. //1. node==null
  190. if (node == null) {
  191. return node;
  192. }
  193. //2.未找到key
  194. if (key < node.key) {
  195. //未找到key,且key小于当前节点key,继续向左
  196. node.left = doRemove(node.left, key);
  197. } else if (key > node.key) {
  198. //向右找
  199. node.right = doRemove(node.right, key);
  200. } else {
  201. //3.找到key
  202. if (node.left == null && node.right == null) {
  203. //3.1 没有子节点
  204. return null;
  205. } else if (node.left != null && node.right == null) {
  206. //3.2 一个子节点(左节点)
  207. node = node.left;
  208. } else if (node.left == null && node.right != null) {
  209. //3.2 一个子节点(右节点)
  210. node = node.right;
  211. } else {
  212. //3.3 两个子节点
  213. //找到他最小的后继节点,右子树向左找到底
  214. AVLNode s=node;
  215. while (s.left!=null){
  216. s=s.left;
  217. }
  218. //s即为后继节点,将节点删除并重新修正右子树
  219. s.right=doRemove(s.right,s.key);
  220. //左子树为s.left,右子树为原删除节点的左子树
  221. s.left=node.left;
  222. node=s;
  223. }
  224. }
  225. //4.更新高度
  226. updateHeight(node);
  227. //5.检查是否失衡
  228. return checkBalance(node);
  229. }
  230. }

11. 红黑树

红黑树也是一种自平衡的二叉搜索树,较之 AVL,插入和删除时旋转次数更少
红黑树特性
        1.所有节点都有两种颜色:红与黑
        2.所有 null 视为黑色
        3.红色节点不能相邻
        4.根节点是黑色
        5.从根到任意一个叶子节点,路径中的黑色节点数一样(黑色完美平衡)

补充:黑色叶子结点一般是成对出现,单独出现必定不平衡

11.1 node内部类

  1. private static class Node {
  2. int key;
  3. Object value;
  4. Node left;
  5. Node right;
  6. Node parent;//父节点
  7. Color color = RED;//颜色
  8. //是否是左孩子,左未true,右为false
  9. boolean isLeftChild() {
  10. return parent != null && this == parent.left;
  11. }
  12. //获取叔叔节点
  13. Node uncle() {
  14. //有父节点,和父节点的父节点才能有叔叔节点
  15. if (parent == null || parent.parent == null) {
  16. return null;
  17. }
  18. if (parent.isLeftChild()) {
  19. //如果父亲为左子节点则返回右子节点,
  20. return parent.parent.right;
  21. } else {
  22. //如果父亲为右子节点则返回左子节点
  23. return parent.parent.left;
  24. }
  25. }
  26. //获取兄弟节点
  27. Node sibling() {
  28. if(parent==null){
  29. return null;
  30. }
  31. if(this.isLeftChild()){
  32. return parent.right;
  33. }else {
  34. return parent.left;
  35. }
  36. }
  37. }

11.2 判断颜色

  1. //判断颜色
  2. boolean isRed(Node node){
  3. return node!=null&&node.color==RED;
  4. }
  5. boolean isBlack(Node node){
  6. return node==null||node.color==BLACK;
  7. }

11.3 左旋和右旋

  1. //和AVL树的不同
  2. // 右旋1.父(Parent)的处理2.旋转后新根的父子关系方法内处理
  3. void rotateRight(Node pink) {
  4. //获取pink的父级几点
  5. Node parent = pink.parent;
  6. //旋转
  7. Node yellow = pink.left;
  8. Node gree = yellow.right;
  9. //右旋之后换色节点的右子结点变为Pink
  10. yellow.right = pink;
  11. //之前黄色节点的左子结点赋值给pink,完成右旋
  12. pink.left = gree;
  13. if (gree != null) {
  14. //处理父子关系
  15. gree.parent = pink;
  16. }
  17. //处理父子关系
  18. yellow.parent = parent;
  19. pink.parent = yellow;
  20. //如果parent为空则根节点为yellow
  21. if (parent == null) {
  22. root = yellow;
  23. } else if (parent.left == pink) {
  24. //处理父子关系,yellow代替pink
  25. parent.left = yellow;
  26. } else {
  27. parent.right = yellow;
  28. }
  29. }
  30. void rotateLeft(Node pink) {
  31. //获取pink的父级几点
  32. Node parent = pink.parent;
  33. //旋转
  34. Node yellow = pink.right;
  35. Node gree = yellow.left;
  36. //右旋之后换色节点的右子结点变为Pink
  37. yellow.left = pink;
  38. //之前黄色节点的左子结点赋值给pink,完成右旋
  39. pink.right = gree;
  40. if (gree != null) {
  41. //处理父子关系
  42. gree.parent = pink;
  43. }
  44. //处理父子关系
  45. yellow.parent = parent;
  46. pink.parent = yellow;
  47. //如果parent为空则根节点为yellow
  48. if (parent == null) {
  49. root = yellow;
  50. } else if (parent.right == pink) {
  51. //处理父子关系,yellow代替pink
  52. parent.right = yellow;
  53. } else {
  54. parent.left = yellow;
  55. }
  56. }

11.4 新增或更新

  1. //新增或更新
  2. void put(int key, Object value) {
  3. Node p = root;
  4. Node parent = null;
  5. while (p != null) {
  6. parent = p;
  7. if (key < p.key) {
  8. //向左找
  9. p = p.left;
  10. } else if (key > p.key) {
  11. p = p.right;
  12. } else {
  13. //更新
  14. p.value = value;
  15. return;
  16. }
  17. }
  18. //插入
  19. Node interestNode = new Node(key, value);
  20. //如果parent为空
  21. if (parent == null) {
  22. root = interestNode;
  23. } else if (key < parent.key) {
  24. parent.left = interestNode;
  25. interestNode.parent = parent;
  26. } else {
  27. parent.right = interestNode;
  28. interestNode.parent = parent;
  29. }
  30. fixRedRed(interestNode);
  31. }
  32. /*
  33. * 1.所有节点都有两种颜色:红与黑
  34. * 2.所有 null 视为黑色
  35. * 3.红色节点不能相邻
  36. * 4.根节点是黑色
  37. * 5.从根到任意一个叶子节点,路径中的黑色节点数一样(黑色完美平衡)
  38. * */
  39. //修复红红不平衡
  40. void fixRedRed(Node x) {
  41. /*
  42. * 插入节点均视为红色
  43. * 插入节点的父亲为红色
  44. * 触发红红相邻
  45. * case 3:叔叔为红色
  46. * case 4:叔叔为黑色
  47. * */
  48. //case 1:插入节点为根节点,将根节点变黑
  49. if (x == root) {
  50. x.color = BLACK;
  51. return;
  52. }
  53. //case 2:插入节点的父亲若为黑色树的红黑性质不变,无需调整
  54. if (isBlack(x.parent)) {
  55. return;
  56. }
  57. Node parent = x.parent;
  58. Node uncle = x.uncle();
  59. Node grandParent = parent.parent;
  60. //插入节点的父亲为红色
  61. if (isRed(uncle)) {
  62. //红红相邻叔叔为红色时(仅通过变色即可)
  63. /*
  64. * 为了保证黑色平衡,连带的叔叔也变为黑色·
  65. * 祖父如果是黑色不变,会造成这颗子树黑色过多,因此祖父节点变为红色祖父如果变成红色,
  66. * 可能会接着触发红红相邻,因此对将祖父进行递归调整,祖父的父亲变为黑色
  67. * */
  68. parent.color = BLACK;
  69. uncle.color = BLACK;
  70. grandParent.color = RED;
  71. fixRedRed(grandParent);
  72. return;
  73. } else {
  74. //触发红红相邻叔叔为黑色
  75. /*
  76. * 1.父亲为左孩子,插入节点也是左孩子,此时即 LL不平衡(右旋一次)
  77. * 2.父亲为左孩子,插入节点是右孩子,此时即 LR不平衡(父亲左旋,祖父右旋)
  78. * 3.父亲为右孩子,插入节点也是右孩子,此时即 RR不平衡(左旋一次)
  79. * 4.父亲为右孩子,插入节点是左孩子,此时即 RL不平衡(父亲右旋,祖父左旋)
  80. *
  81. */
  82. if (parent.isLeftChild() && x.isLeftChild()) {
  83. //如果父亲为左子节点,查询节点也为左子结点即为LL(祖父右旋处理)
  84. //父节点变黑(和叔叔节点同为黑色)
  85. parent.color = BLACK;
  86. //祖父节点变红
  87. grandParent.color = RED;
  88. rotateRight(grandParent);
  89. } else if (parent.isLeftChild() && !x.isLeftChild()) {
  90. //parent为左子节点,插入节点为右子节点,LR(父亲左旋,祖父右旋)
  91. rotateLeft(parent);
  92. //插入节点变为黑色
  93. x.color=BLACK;
  94. //祖父变为红色
  95. grandParent.color=RED;
  96. rotateRight(grandParent);
  97. } else if (!parent.isLeftChild()&&!x.isLeftChild()) {
  98. //父节点变黑(和叔叔节点同为黑色)
  99. parent.color = BLACK;
  100. //祖父节点变红
  101. grandParent.color = RED;
  102. rotateLeft(grandParent);
  103. }else if(!parent.isLeftChild()&&x.isLeftChild()){
  104. rotateRight(parent);
  105. //插入节点变为黑色
  106. x.color=BLACK;
  107. //祖父变为红色
  108. grandParent.color=RED;
  109. rotateLeft(grandParent);
  110. }
  111. }
  112. }

11.5 删除

  1. //删除
  2. /*
  3. * 删除
  4. * 正常删、会用到李代桃僵技巧、遇到黑黑不平衡进行调整
  5. * */
  6. public void remove(int key) {
  7. Node deleted = find(key);
  8. if (deleted == null) {
  9. return;
  10. }
  11. doRemove(deleted);
  12. }
  13. //检测双黑节点删除
  14. /*
  15. *
  16. * 删除节点和剩下节点都是黑触发双黑,双黑意思是,少了一个黑
  17. * case 3:删除节点或剩余节点的兄弟为红此时两个侄子定为黑
  18. * case 4:删除节点或剩余节点的兄弟、和兄弟孩子都为黑
  19. * case 5:删除节点的兄弟为黑,至少一个红侄子
  20. *
  21. * */
  22. private void fixDoubleBlack(Node x) {
  23. //把case3处理为case4和case5
  24. if (x == root) {
  25. return;
  26. }
  27. Node parent = x.parent;
  28. Node sibling = x.sibling();
  29. if (sibling.color == RED) {
  30. //进入case3
  31. if (x.isLeftChild()) {
  32. //如果是做孩子就进行左旋
  33. rotateLeft(parent);
  34. } else {
  35. //如果是右孩子就进行右旋
  36. rotateRight(parent);
  37. }
  38. //父亲颜色变为红色(父亲变色前肯定为黑色)
  39. parent.color = RED;
  40. //兄弟变为黑色
  41. sibling.color = BLACK;
  42. //此时case3 已经被转换为 case4或者case5
  43. fixDoubleBlack(x);
  44. return;
  45. }
  46. //兄弟为黑
  47. //两个侄子都为黑
  48. if (sibling != null) {
  49. if (isBlack(sibling.left) && isBlack(sibling.right)) {
  50. /*
  51. * case 4:被调整节点的兄弟为黑,两个侄于都为黑
  52. * 将兄弟变红, 目的是将删除节点和兄弟那边的黑色高度同时减少1
  53. * 如果父亲是红,则需将父亲变为黑,避免红红,此时路径黑节点数目不变
  54. * 如果父亲是黑,说明这条路径则少了一个黑,再次让父节点触发双黑
  55. * */
  56. //将兄弟变红, 目的是将删除节点和兄弟那边的黑色高度同时减少1
  57. sibling.color = RED;
  58. if (isRed(parent)) {
  59. // 如果父亲是红,则需将父亲变为黑,避免红红,此时路径黑节点数目不变
  60. parent.color = BLACK;
  61. } else {
  62. //如果父亲是黑,说明这条路径则少了一个黑,再次让父节点触发双黑
  63. fixDoubleBlack(parent);
  64. }
  65. } else {
  66. //CASE5 至少有一个侄子不是黑色
  67. /*
  68. *
  69. * case 5:被调整节点的兄弟为黑
  70. * 如果兄弟是左孩子,左侄子是红 LL 不平衡
  71. * 如果兄弟是左孩子,右侄子是红 LR 不平衡
  72. * 如果兄弟是右孩子,右侄于是红 RR 不平衡
  73. * 如果兄弟是右孩子,左侄于是红 RL 不平衡
  74. * */
  75. if(sibling.isLeftChild()&&isRed(sibling.left)){
  76. // 如果兄弟是左孩子,左侄子是红 LL 不平衡
  77. rotateRight(parent);
  78. //兄弟的做孩子变黑
  79. sibling.left.color=BLACK;
  80. //兄弟变成父亲的颜色
  81. sibling.color= parent.color;
  82. //父亲变黑
  83. parent.color=BLACK;
  84. }else if(sibling.isLeftChild()&&isRed(sibling.right)){
  85. //如果兄弟是左孩子,右侄子是红 LR 不平衡
  86. //变色必须在上 否则旋转后会空指针
  87. //兄弟的右孩子变为父节点颜色
  88. sibling.right.color= parent.color;
  89. //父节点变黑
  90. parent.color=BLACK;
  91. rotateLeft(sibling);
  92. rotateRight(parent);
  93. }
  94. }
  95. } else {
  96. fixDoubleBlack(parent);
  97. }
  98. }
  99. private void doRemove(Node deleted) {
  100. Node replaced = findReplaced(deleted);
  101. Node parent = deleted.parent;
  102. if (replaced == null) {
  103. //没有子节点
  104. /* case1:删的是根节点,没有子节点
  105. * 删完了,直接将 root=null
  106. * */
  107. if (deleted == root) {
  108. root = null;
  109. } else {
  110. /*
  111. * Case2:删的是黑,剩下的是红剩下这个红节点变黑
  112. * */
  113. if (isBlack(deleted)) {
  114. //复杂处理,先调整平衡再删除
  115. fixDoubleBlack(deleted);
  116. } else {
  117. //红色不处理
  118. }
  119. //删除的不是根节点且没有孩子
  120. if (deleted.isLeftChild()) {
  121. parent.left = null;
  122. } else {
  123. parent.right = null;
  124. }
  125. deleted.parent = null;
  126. }
  127. return;
  128. } else if (replaced.left == null || replaced.right == null) {
  129. //有一个子节点
  130. /* case1:删的是根节点,有一个子节点
  131. * 用剩余节点替换了根节点的 key,Value,根节点孩子=null,颜色保持黑色 不变
  132. * */
  133. if (deleted == root) {
  134. root.key = replaced.key;
  135. root.value = replaced.value;
  136. root.left = root.right = null;
  137. } else {
  138. //删除的不是根节点但是有一个孩子
  139. if (deleted.isLeftChild()) {
  140. parent.left = replaced;
  141. } else {
  142. parent.right = replaced;
  143. }
  144. replaced.parent = parent;
  145. deleted.right = deleted.left = deleted.parent = null;
  146. if (isBlack(deleted) && isBlack(replaced)) {
  147. //如果删除的是黑色剩下的也是黑色,需要复杂处理,先删除再平衡
  148. fixDoubleBlack(replaced);
  149. } else {
  150. /*
  151. * Case2:删的是黑,剩下的是红剩下这个红节点变黑
  152. * */
  153. replaced.color = BLACK;
  154. }
  155. }
  156. return;
  157. } else {
  158. //两个子节点
  159. //交换删除节点和删除节点的后几点的key,value,这
  160. // 样被删除节点就只有一个子节点或没有子节点了
  161. int t = deleted.key;
  162. deleted.key = replaced.key;
  163. replaced.key = t;
  164. Object v = deleted.value;
  165. deleted.value = replaced.value;
  166. replaced.value = v;
  167. doRemove(replaced);
  168. return;
  169. }
  170. }
  171. private Node find(int key) {
  172. Node p = root;
  173. while (p != null) {
  174. if (key > p.key) {
  175. //key更大向右找
  176. p = p.right;
  177. } else if (key < p.key) {
  178. //向左找
  179. p = p.left;
  180. } else {
  181. return p;
  182. }
  183. }
  184. return null;
  185. }
  186. //查找删除后的剩余节点
  187. private Node findReplaced(Node deleted) {
  188. if (deleted.left == null & deleted.right == null) {
  189. //没有子节点
  190. return null;
  191. } else if (deleted.left == null) {
  192. return deleted.right;
  193. } else if (deleted.right == null) {
  194. return deleted.left;
  195. } else {
  196. Node s = deleted.right;
  197. while (s != null) {
  198. //右子树的最小值
  199. s = s.left;
  200. }
  201. return s;
  202. }
  203. }
  204. }

 11.6 完整代码

  1. package org.alogorithm.tree;
  2. import static org.alogorithm.tree.RedBlackTree.Color.BLACK;
  3. import static org.alogorithm.tree.RedBlackTree.Color.RED;
  4. public class RedBlackTree {
  5. enum Color {RED, BLACK}
  6. private Node root;
  7. private static class Node {
  8. int key;
  9. Object value;
  10. Node left;
  11. Node right;
  12. Node parent;//父节点
  13. Color color = RED;//颜色
  14. public Node() {
  15. }
  16. public Node(int key, Object value) {
  17. this.key = key;
  18. this.value = value;
  19. }
  20. //是否是左孩子,左未true,右为false
  21. boolean isLeftChild() {
  22. return parent != null && this == parent.left;
  23. }
  24. //获取叔叔节点
  25. Node uncle() {
  26. //有父节点,和父节点的父节点才能有叔叔节点
  27. if (parent == null || parent.parent == null) {
  28. return null;
  29. }
  30. if (parent.isLeftChild()) {
  31. //如果父亲为左子节点则返回右子节点,
  32. return parent.parent.right;
  33. } else {
  34. //如果父亲为右子节点则返回左子节点
  35. return parent.parent.left;
  36. }
  37. }
  38. //获取兄弟节点
  39. Node sibling() {
  40. if (parent == null) {
  41. return null;
  42. }
  43. if (this.isLeftChild()) {
  44. return parent.right;
  45. } else {
  46. return parent.left;
  47. }
  48. }
  49. }
  50. //判断颜色
  51. boolean isRed(Node node) {
  52. return node != null && node.color == RED;
  53. }
  54. boolean isBlack(Node node) {
  55. return node == null || node.color == BLACK;
  56. }
  57. //和AVL树的不同
  58. // 右旋1.父(Parent)的处理2.旋转后新根的父子关系方法内处理
  59. void rotateRight(Node pink) {
  60. //获取pink的父级几点
  61. Node parent = pink.parent;
  62. //旋转
  63. Node yellow = pink.left;
  64. Node gree = yellow.right;
  65. //右旋之后换色节点的右子结点变为Pink
  66. yellow.right = pink;
  67. //之前黄色节点的左子结点赋值给pink,完成右旋
  68. pink.left = gree;
  69. if (gree != null) {
  70. //处理父子关系
  71. gree.parent = pink;
  72. }
  73. //处理父子关系
  74. yellow.parent = parent;
  75. pink.parent = yellow;
  76. //如果parent为空则根节点为yellow
  77. if (parent == null) {
  78. root = yellow;
  79. } else if (parent.left == pink) {
  80. //处理父子关系,yellow代替pink
  81. parent.left = yellow;
  82. } else {
  83. parent.right = yellow;
  84. }
  85. }
  86. void rotateLeft(Node pink) {
  87. //获取pink的父级几点
  88. Node parent = pink.parent;
  89. //旋转
  90. Node yellow = pink.right;
  91. Node gree = yellow.left;
  92. //右旋之后换色节点的右子结点变为Pink
  93. yellow.left = pink;
  94. //之前黄色节点的左子结点赋值给pink,完成右旋
  95. pink.right = gree;
  96. if (gree != null) {
  97. //处理父子关系
  98. gree.parent = pink;
  99. }
  100. //处理父子关系
  101. yellow.parent = parent;
  102. pink.parent = yellow;
  103. //如果parent为空则根节点为yellow
  104. if (parent == null) {
  105. root = yellow;
  106. } else if (parent.right == pink) {
  107. //处理父子关系,yellow代替pink
  108. parent.right = yellow;
  109. } else {
  110. parent.left = yellow;
  111. }
  112. }
  113. //新增或更新
  114. void put(int key, Object value) {
  115. Node p = root;
  116. Node parent = null;
  117. while (p != null) {
  118. parent = p;
  119. if (key < p.key) {
  120. //向左找
  121. p = p.left;
  122. } else if (key > p.key) {
  123. p = p.right;
  124. } else {
  125. //更新
  126. p.value = value;
  127. return;
  128. }
  129. }
  130. //插入
  131. Node interestNode = new Node(key, value);
  132. //如果parent为空
  133. if (parent == null) {
  134. root = interestNode;
  135. } else if (key < parent.key) {
  136. parent.left = interestNode;
  137. interestNode.parent = parent;
  138. } else {
  139. parent.right = interestNode;
  140. interestNode.parent = parent;
  141. }
  142. fixRedRed(interestNode);
  143. }
  144. /*
  145. * 1.所有节点都有两种颜色:红与黑
  146. * 2.所有 null 视为黑色
  147. * 3.红色节点不能相邻
  148. * 4.根节点是黑色
  149. * 5.从根到任意一个叶子节点,路径中的黑色节点数一样(黑色完美平衡)
  150. * */
  151. //修复红红不平衡
  152. void fixRedRed(Node x) {
  153. /*
  154. * 插入节点均视为红色
  155. * 插入节点的父亲为红色
  156. * 触发红红相邻
  157. * case 3:叔叔为红色
  158. * case 4:叔叔为黑色
  159. * */
  160. //case 1:插入节点为根节点,将根节点变黑
  161. if (x == root) {
  162. x.color = BLACK;
  163. return;
  164. }
  165. //case 2:插入节点的父亲若为黑色树的红黑性质不变,无需调整
  166. if (isBlack(x.parent)) {
  167. return;
  168. }
  169. Node parent = x.parent;
  170. Node uncle = x.uncle();
  171. Node grandParent = parent.parent;
  172. //插入节点的父亲为红色
  173. if (isRed(uncle)) {
  174. //红红相邻叔叔为红色时(仅通过变色即可)
  175. /*
  176. * 为了保证黑色平衡,连带的叔叔也变为黑色·
  177. * 祖父如果是黑色不变,会造成这颗子树黑色过多,因此祖父节点变为红色祖父如果变成红色,
  178. * 可能会接着触发红红相邻,因此对将祖父进行递归调整,祖父的父亲变为黑色
  179. * */
  180. parent.color = BLACK;
  181. uncle.color = BLACK;
  182. grandParent.color = RED;
  183. fixRedRed(grandParent);
  184. return;
  185. } else {
  186. //触发红红相邻叔叔为黑色
  187. /*
  188. * 1.父亲为左孩子,插入节点也是左孩子,此时即 LL不平衡(右旋一次)
  189. * 2.父亲为左孩子,插入节点是右孩子,此时即 LR不平衡(父亲左旋,祖父右旋)
  190. * 3.父亲为右孩子,插入节点也是右孩子,此时即 RR不平衡(左旋一次)
  191. * 4.父亲为右孩子,插入节点是左孩子,此时即 RL不平衡(父亲右旋,祖父左旋)
  192. *
  193. */
  194. if (parent.isLeftChild() && x.isLeftChild()) {
  195. //如果父亲为左子节点,查询节点也为左子结点即为LL(祖父右旋处理)
  196. //父节点变黑(和叔叔节点同为黑色)
  197. parent.color = BLACK;
  198. //祖父节点变红
  199. grandParent.color = RED;
  200. rotateRight(grandParent);
  201. } else if (parent.isLeftChild() && !x.isLeftChild()) {
  202. //parent为左子节点,插入节点为右子节点,LR(父亲左旋,祖父右旋)
  203. rotateLeft(parent);
  204. //插入节点变为黑色
  205. x.color = BLACK;
  206. //祖父变为红色
  207. grandParent.color = RED;
  208. rotateRight(grandParent);
  209. } else if (!parent.isLeftChild() && !x.isLeftChild()) {
  210. //父节点变黑(和叔叔节点同为黑色)
  211. parent.color = BLACK;
  212. //祖父节点变红
  213. grandParent.color = RED;
  214. rotateLeft(grandParent);
  215. } else if (!parent.isLeftChild() && x.isLeftChild()) {
  216. rotateRight(parent);
  217. //插入节点变为黑色
  218. x.color = BLACK;
  219. //祖父变为红色
  220. grandParent.color = RED;
  221. rotateLeft(grandParent);
  222. }
  223. }
  224. }
  225. //删除
  226. /*
  227. * 删除
  228. * 正常删、会用到李代桃僵技巧、遇到黑黑不平衡进行调整
  229. * */
  230. public void remove(int key) {
  231. Node deleted = find(key);
  232. if (deleted == null) {
  233. return;
  234. }
  235. doRemove(deleted);
  236. }
  237. //检测双黑节点删除
  238. /*
  239. *
  240. * 删除节点和剩下节点都是黑触发双黑,双黑意思是,少了一个黑
  241. * case 3:删除节点或剩余节点的兄弟为红此时两个侄子定为黑
  242. * case 4:删除节点或剩余节点的兄弟、和兄弟孩子都为黑
  243. * case 5:删除节点的兄弟为黑,至少一个红侄子
  244. *
  245. * */
  246. private void fixDoubleBlack(Node x) {
  247. //把case3处理为case4和case5
  248. if (x == root) {
  249. return;
  250. }
  251. Node parent = x.parent;
  252. Node sibling = x.sibling();
  253. if (sibling.color == RED) {
  254. //进入case3
  255. if (x.isLeftChild()) {
  256. //如果是做孩子就进行左旋
  257. rotateLeft(parent);
  258. } else {
  259. //如果是右孩子就进行右旋
  260. rotateRight(parent);
  261. }
  262. //父亲颜色变为红色(父亲变色前肯定为黑色)
  263. parent.color = RED;
  264. //兄弟变为黑色
  265. sibling.color = BLACK;
  266. //此时case3 已经被转换为 case4或者case5
  267. fixDoubleBlack(x);
  268. return;
  269. }
  270. //兄弟为黑
  271. //两个侄子都为黑
  272. if (sibling != null) {
  273. if (isBlack(sibling.left) && isBlack(sibling.right)) {
  274. /*
  275. * case 4:被调整节点的兄弟为黑,两个侄于都为黑
  276. * 将兄弟变红, 目的是将删除节点和兄弟那边的黑色高度同时减少1
  277. * 如果父亲是红,则需将父亲变为黑,避免红红,此时路径黑节点数目不变
  278. * 如果父亲是黑,说明这条路径则少了一个黑,再次让父节点触发双黑
  279. * */
  280. //将兄弟变红, 目的是将删除节点和兄弟那边的黑色高度同时减少1
  281. sibling.color = RED;
  282. if (isRed(parent)) {
  283. // 如果父亲是红,则需将父亲变为黑,避免红红,此时路径黑节点数目不变
  284. parent.color = BLACK;
  285. } else {
  286. //如果父亲是黑,说明这条路径则少了一个黑,再次让父节点触发双黑
  287. fixDoubleBlack(parent);
  288. }
  289. } else {
  290. //CASE5 至少有一个侄子不是黑色
  291. /*
  292. *
  293. * case 5:被调整节点的兄弟为黑
  294. * 如果兄弟是左孩子,左侄子是红 LL 不平衡
  295. * 如果兄弟是左孩子,右侄子是红 LR 不平衡
  296. * 如果兄弟是右孩子,右侄于是红 RR 不平衡
  297. * 如果兄弟是右孩子,左侄于是红 RL 不平衡
  298. * */
  299. if(sibling.isLeftChild()&&isRed(sibling.left)){
  300. // 如果兄弟是左孩子,左侄子是红 LL 不平衡
  301. rotateRight(parent);
  302. //兄弟的做孩子变黑
  303. sibling.left.color=BLACK;
  304. //兄弟变成父亲的颜色
  305. sibling.color= parent.color;
  306. //父亲变黑
  307. parent.color=BLACK;
  308. }else if(sibling.isLeftChild()&&isRed(sibling.right)){
  309. //如果兄弟是左孩子,右侄子是红 LR 不平衡
  310. //变色必须在上 否则旋转后会空指针
  311. //兄弟的右孩子变为父节点颜色
  312. sibling.right.color= parent.color;
  313. //父节点变黑
  314. parent.color=BLACK;
  315. rotateLeft(sibling);
  316. rotateRight(parent);
  317. }
  318. }
  319. } else {
  320. fixDoubleBlack(parent);
  321. }
  322. }
  323. private void doRemove(Node deleted) {
  324. Node replaced = findReplaced(deleted);
  325. Node parent = deleted.parent;
  326. if (replaced == null) {
  327. //没有子节点
  328. /* case1:删的是根节点,没有子节点
  329. * 删完了,直接将 root=null
  330. * */
  331. if (deleted == root) {
  332. root = null;
  333. } else {
  334. /*
  335. * Case2:删的是黑,剩下的是红剩下这个红节点变黑
  336. * */
  337. if (isBlack(deleted)) {
  338. //复杂处理,先调整平衡再删除
  339. fixDoubleBlack(deleted);
  340. } else {
  341. //红色不处理
  342. }
  343. //删除的不是根节点且没有孩子
  344. if (deleted.isLeftChild()) {
  345. parent.left = null;
  346. } else {
  347. parent.right = null;
  348. }
  349. deleted.parent = null;
  350. }
  351. return;
  352. } else if (replaced.left == null || replaced.right == null) {
  353. //有一个子节点
  354. /* case1:删的是根节点,有一个子节点
  355. * 用剩余节点替换了根节点的 key,Value,根节点孩子=null,颜色保持黑色 不变
  356. * */
  357. if (deleted == root) {
  358. root.key = replaced.key;
  359. root.value = replaced.value;
  360. root.left = root.right = null;
  361. } else {
  362. //删除的不是根节点但是有一个孩子
  363. if (deleted.isLeftChild()) {
  364. parent.left = replaced;
  365. } else {
  366. parent.right = replaced;
  367. }
  368. replaced.parent = parent;
  369. deleted.right = deleted.left = deleted.parent = null;
  370. if (isBlack(deleted) && isBlack(replaced)) {
  371. //如果删除的是黑色剩下的也是黑色,需要复杂处理,先删除再平衡
  372. fixDoubleBlack(replaced);
  373. } else {
  374. /*
  375. * Case2:删的是黑,剩下的是红剩下这个红节点变黑
  376. * */
  377. replaced.color = BLACK;
  378. }
  379. }
  380. return;
  381. } else {
  382. //两个子节点
  383. //交换删除节点和删除节点的后几点的key,value,这
  384. // 样被删除节点就只有一个子节点或没有子节点了
  385. int t = deleted.key;
  386. deleted.key = replaced.key;
  387. replaced.key = t;
  388. Object v = deleted.value;
  389. deleted.value = replaced.value;
  390. replaced.value = v;
  391. doRemove(replaced);
  392. return;
  393. }
  394. }
  395. private Node find(int key) {
  396. Node p = root;
  397. while (p != null) {
  398. if (key > p.key) {
  399. //key更大向右找
  400. p = p.right;
  401. } else if (key < p.key) {
  402. //向左找
  403. p = p.left;
  404. } else {
  405. return p;
  406. }
  407. }
  408. return null;
  409. }
  410. //查找删除后的剩余节点
  411. private Node findReplaced(Node deleted) {
  412. if (deleted.left == null & deleted.right == null) {
  413. //没有子节点
  414. return null;
  415. } else if (deleted.left == null) {
  416. return deleted.right;
  417. } else if (deleted.right == null) {
  418. return deleted.left;
  419. } else {
  420. Node s = deleted.right;
  421. while (s != null) {
  422. //右子树的最小值
  423. s = s.left;
  424. }
  425. return s;
  426. }
  427. }
  428. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/代码探险家/article/detail/903692
推荐阅读
相关标签
  

闽ICP备14008679号