数据结构和算法入门

打印 上一主题 下一主题

主题 529|帖子 529|积分 1587

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 中,整数除法(/)对整数操作时会向下取整,结果仍然是一个整数。例如,假如 i 和 j 都是很大的数,且它们相加结果大于 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.    
  24.     public static int binarySearch(int[] arr, int target){
  25.         //设置 i跟j 初始值
  26.         int i=0;
  27.         int j= arr.length-1;
  28.         //如果i>j,则表示并未找到该值
  29.         while (i<=j){
  30.             int m=(i+j)>>>1;
  31. //            int m=(i+j)/2;
  32.             if (target<arr[m]){
  33.                 //目标在左侧
  34.                 j=m-1;
  35.             }else if(target>arr[m]){
  36.                 //目标在右侧
  37.                 i=m+1;
  38.             }else{
  39.                 //相等
  40.                 return m;
  41.             }
  42.         }
  43.         return -1;
  44.     }
复制代码
    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==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与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字节的整数倍,不足的要用对齐字节补足)
  例如:
   
  1. 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 四种失衡环境

  
  1. LL
  2.     -失衡节点的 bf >1,即左边更高
  3.     -失衡节点的左孩子的bf>=0即左孩子这边也是左边更高或等
  4.     一次右旋可以恢复平衡
  5. LR
  6.     -失衡节点的 bf >1,即左边更高
  7.     -失衡节点的左孩子的bf<0 即左孩子这边是右边更高
  8.     左子节点先左旋,将树修正为LL情况,
  9.     然后失衡节点再右旋,恢复平衡
  10. RL
  11.     -失衡节点的 bf <-1,即右边更高
  12.     -失衡节点的右孩子的bf>0,即右孩子这边左边更高
  13.     右子节点先右旋,将树修正为RR情况,
  14.     然后失衡节点再左旋,恢复平衡
  15. RR
  16.     -失衡节点的 bf<-1,即右边更高
  17.     -失衡节点的右孩子的bf<=0,即右孩子这边右边更高或等高
  18.     一次左旋可以恢复平衡
复制代码
   
  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;public class AVLTree {    static class AVLNode {        int key;        int height = 1;//高度初始值1        AVLNode left, right;        private AVLNode root;        Object value;        public AVLNode(int key, Object value) {            this.key = key;            this.value = value;        }        public AVLNode(int key, AVLNode left, AVLNode right, AVLNode root) {            this.key = key;            this.left = left;            this.right = right;            this.root = root;        }    }    //处理节点高度    private int haight(AVLNode node) {        return node == null ? 0 : node.height;    }    //增、删、旋转更新节点高度    //最大高度+1    public void updateHeight(AVLNode treeNode) {        treeNode.height = Integer.max(haight(treeNode.left), haight(treeNode.right)) + 1;    }    /*    平衡因子:一个节点左子树高度-右子树高度所得结果     小于1平衡:(0,1,-1)     大于1不平衡         >1:左边高         <-1:右边高     */    public int bf(AVLNode avlNode) {        return haight(avlNode.left) - haight(avlNode.right);    }    //四种失衡环境        /*        LL            -失衡节点的 bf >1,即左边更高            -失衡节点的左孩子的bf>=0即左孩子这边也是左边更高或等            一次右旋可以规复平衡        LR            -失衡节点的 bf >1,即左边更高            -失衡节点的左孩子的bf<0 即左孩子这边是右边更高            左子节点先左旋,将树修正为LL环境,            然后失衡节点再右旋,规复平衡        RL            -失衡节点的 bf <-1,即右边更高            -失衡节点的右孩子的bf>0,即右孩子这边左边更高            右子节点先右旋,将树修正为RR环境,            然后失衡节点再左旋,规复平衡        RR            -失衡节点的 bf<-1,即右边更高            -失衡节点的右孩子的bf<=0,即右孩子这边右边更高或等高            一次左旋可以规复平衡*/    //右旋    /**     * @Description 返回旋转后的节点     * @Param [avlNode] 必要旋转的节点     **/    private AVLNode rightRotate(AVLNode redNode) {        AVLNode yellowNode = redNode.left;        /*         *黄色节点有右子节点,给右子节点重新找父级节点         *由于二叉搜索树特性,某个节点的左子节点肯定小于 本身,右子节点肯定大于本身         * 故:yelllow的右子节点肯定大于yellow且小于rea,         *    所以,gree可以作为red的左子结点         * */        /*        AVLNode greeNode = yellowNode.right;        redNode.left = greeNode;        */        redNode.left = yellowNode.right;        yellowNode.right = redNode;        //更新高度,赤色和黄色都会改变        updateHeight(redNode);        updateHeight(yellowNode);        return yellowNode;    }    //左旋    private AVLNode leftRotate(AVLNode redNode) {        //左旋和右旋操作相反        AVLNode yellowNode = redNode.right;        //处理yellow的子节点        redNode.right = yellowNode.left;        //yellow变为跟,原red比yellow小,为yellow的left        yellowNode.left = redNode;        updateHeight(redNode);        updateHeight(yellowNode);        return yellowNode;    }    /*    * LR            -失衡节点的 bf >1,即左边更高            -失衡节点的左孩子的bf<0 即左孩子这边是右边更高            左子节点先左旋,将树修正为LL环境,            然后失衡节点再右旋,规复平衡    * */    //先左旋再右旋    private AVLNode leftRightRotate(AVLNode node) {        //修正左子结点LL        node.left = leftRotate(node.left);        return rightRotate(node);    }    /*    *   RL            -失衡节点的 bf <-1,即右边更高            -失衡节点的右孩子的bf>0,即右孩子这边左边更高            右子节点先右旋,将树修正为RR环境,            然后失衡节点再左旋,规复平衡    * */    //先右旋再左旋    private AVLNode rightLeftRotate(AVLNode node) {        //修正右子节点为RR        node.right = rightRotate(node.left);        return leftRotate(node);    }    //检查节点是否失衡,重新平衡
  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.     }    AVLNode root;    public void put(int key, Object value) {        doPut(root, key, value);    }    //找空位并添加新的节点    private AVLNode doPut(AVLNode node, int key, Object value) {        /*         * 1.找到空位,创建新节点         * 2.key 已存在 更新位置         * 3.继续寻找         *  */        //未找到        if (node == null) {            return new AVLNode(key, value);        }        //找到了节点 重新赋值        if (key == node.key) {            node.value = value;            return node;        }        //继续查找        if (key < node.key) {            //继续向左,并创建父子关系            node.left = doPut(node.left, key, value);        } else {            //向右找,并创建父子关系            node.right = doPut(node.right, key, value);        }        //更新节点高度        updateHeight(node);        //重新平衡树        return checkBalance(node);    }    //删除
  30.     public void remove(int key) {
  31.         root = doRemove(root, key);
  32.     }
  33.     private AVLNode doRemove(AVLNode node, int key) {
  34.         //1. node==null
  35.         if (node == null) {
  36.             return node;
  37.         }
  38.         //2.未找到key
  39.         if (key < node.key) {
  40.             //未找到key,且key小于当前节点key,继续向左
  41.             node.left = doRemove(node.left, key);
  42.         } else if (key > node.key) {
  43.             //向右找
  44.             node.right = doRemove(node.right, key);
  45.         } else {
  46.             //3.找到key
  47.             if (node.left == null && node.right == null) {
  48.                 //3.1 没有子节点
  49.                 return null;
  50.             } else if (node.left != null && node.right == null) {
  51.                 //3.2 一个子节点(左节点)
  52.                 node = node.left;
  53.             } else if (node.left == null && node.right != null) {
  54.                 //3.2 一个子节点(右节点)
  55.                 node = node.right;
  56.             } else {
  57.                 //3.3 两个子节点
  58.                 //找到他最小的后继节点,右子树向左找到底
  59.                 AVLNode s=node;
  60.                 while (s.left!=null){
  61.                     s=s.left;
  62.                 }
  63.                 //s即为后继节点,将节点删除并重新修正右子树
  64.                 s.right=doRemove(s.right,s.key);
  65.                 //左子树为s.left,右子树为原删除节点的左子树
  66.                 s.left=node.left;
  67.                 node=s;
  68.             }
  69.         }
  70.         //4.更新高度
  71.         updateHeight(node);
  72.         //5.检查是否失衡
  73.         return checkBalance(node);
  74.     }}
复制代码
   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;import static org.alogorithm.tree.RedBlackTree.Color.BLACK;import static org.alogorithm.tree.RedBlackTree.Color.RED;public class RedBlackTree {    enum Color {RED, BLACK}    private Node root;    private static class Node {        int key;        Object value;        Node left;        Node right;        Node parent;//父节点        Color color = RED;//颜色        public Node() {        }        public Node(int key, Object value) {            this.key = key;            this.value = value;        }        //是否是左孩子,左未true,右为false        boolean isLeftChild() {            return parent != null && this == parent.left;        }        //获取叔叔节点        Node uncle() {            //有父节点,和父节点的父节点才气有叔叔节点            if (parent == null || parent.parent == null) {                return null;            }            if (parent.isLeftChild()) {                //假如父亲为左子节点则返回右子节点,                return parent.parent.right;            } else {                //假如父亲为右子节点则返回左子节点                return parent.parent.left;            }        }        //获取兄弟节点        Node sibling() {            if (parent == null) {                return null;            }            if (this.isLeftChild()) {                return parent.right;            } else {                return parent.left;            }        }    }    //判定颜色    boolean isRed(Node node) {        return node != null && node.color == RED;    }    boolean isBlack(Node node) {        return node == null || node.color == BLACK;    }    //和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.     }    //新增或更新    void put(int key, Object value) {        Node p = root;        Node parent = null;        while (p != null) {            parent = p;            if (key < p.key) {                //向左找                p = p.left;            } else if (key > p.key) {                p = p.right;            } else {                //更新                p.value = value;                return;            }        }        //插入        Node interestNode = new Node(key, value);        //假如parent为空        if (parent == null) {            root = interestNode;        } else if (key < parent.key) {            parent.left = interestNode;            interestNode.parent = parent;        } else {            parent.right = interestNode;            interestNode.parent = parent;        }        fixRedRed(interestNode);    }    /*     * 1.所有节点都有两种颜色:红与黑     * 2.所有 null 视为玄色     * 3.赤色节点不能相邻     * 4.根节点是玄色     * 5.从根到任意一个叶子节点,路径中的玄色节点数一样(玄色完美平衡)     * */    //修复红红不平衡    void fixRedRed(Node x) {        /*         * 插入节点均视为赤色         * 插入节点的父亲为赤色         * 触发红红相邻         * case 3:叔叔为赤色         * case 4:叔叔为玄色         * */        //case 1:插入节点为根节点,将根节点变黑        if (x == root) {            x.color = BLACK;            return;        }        //case 2:插入节点的父亲若为玄色树的红黑性质不变,无需调整        if (isBlack(x.parent)) {            return;        }        Node parent = x.parent;        Node uncle = x.uncle();        Node grandParent = parent.parent;        //插入节点的父亲为赤色        if (isRed(uncle)) {            //红红相邻叔叔为赤色时(仅通过变色即可)            /*             * 为了包管玄色平衡,连带的叔叔也变为玄色·             * 祖父假如是玄色不变,会造成这颗子树玄色过多,因此祖父节点变为赤色祖父假如酿成赤色,             * 可能会接着触发红红相邻,因此对将祖父举行递归调整,祖父的父亲变为玄色             * */            parent.color = BLACK;            uncle.color = BLACK;            grandParent.color = RED;            fixRedRed(grandParent);            return;        } else {            //触发红红相邻叔叔为玄色            /*             * 1.父亲为左孩子,插入节点也是左孩子,此时即 LL不平衡(右旋一次)             * 2.父亲为左孩子,插入节点是右孩子,此时即 LR不平衡(父亲左旋,祖父右旋)             * 3.父亲为右孩子,插入节点也是右孩子,此时即 RR不平衡(左旋一次)             * 4.父亲为右孩子,插入节点是左孩子,此时即 RL不平衡(父亲右旋,祖父左旋)             *             */            if (parent.isLeftChild() && x.isLeftChild()) {                //假如父亲为左子节点,查询节点也为左子结点即为LL(祖父右旋处理)                //父节点变黑(和叔叔节点同为玄色)                parent.color = BLACK;                //祖父节点变红                grandParent.color = RED;                rotateRight(grandParent);            } else if (parent.isLeftChild() && !x.isLeftChild()) {                //parent为左子节点,插入节点为右子节点,LR(父亲左旋,祖父右旋)                rotateLeft(parent);                //插入节点变为玄色                x.color = BLACK;                //祖父变为赤色                grandParent.color = RED;                rotateRight(grandParent);            } else if (!parent.isLeftChild() && !x.isLeftChild()) {                //父节点变黑(和叔叔节点同为玄色)                parent.color = BLACK;                //祖父节点变红                grandParent.color = RED;                rotateLeft(grandParent);            } else if (!parent.isLeftChild() && x.isLeftChild()) {                rotateRight(parent);                //插入节点变为玄色                x.color = BLACK;                //祖父变为赤色                grandParent.color = RED;                rotateLeft(grandParent);            }        }    }    //删除
  57.     /*
  58.      * 删除
  59.      * 正常删、会用到李代桃僵技巧、遇到黑黑不平衡进行调整
  60.      * */
  61.     public void remove(int key) {
  62.         Node deleted = find(key);
  63.         if (deleted == null) {
  64.             return;
  65.         }
  66.         doRemove(deleted);
  67.     }
  68.     //检测双黑节点删除
  69.     /*
  70.      *
  71.      * 删除节点和剩下节点都是黑触发双黑,双黑意思是,少了一个黑
  72.      * case 3:删除节点或剩余节点的兄弟为红此时两个侄子定为黑
  73.      * case 4:删除节点或剩余节点的兄弟、和兄弟孩子都为黑
  74.      * case 5:删除节点的兄弟为黑,至少一个红侄子
  75.      *
  76.      * */
  77.     private void fixDoubleBlack(Node x) {
  78.         //把case3处理为case4和case5
  79.         if (x == root) {
  80.             return;
  81.         }
  82.         Node parent = x.parent;
  83.         Node sibling = x.sibling();
  84.         if (sibling.color == RED) {
  85.             //进入case3
  86.             if (x.isLeftChild()) {
  87.                 //如果是做孩子就进行左旋
  88.                 rotateLeft(parent);
  89.             } else {
  90.                 //如果是右孩子就进行右旋
  91.                 rotateRight(parent);
  92.             }
  93.             //父亲颜色变为红色(父亲变色前肯定为黑色)
  94.             parent.color = RED;
  95.             //兄弟变为黑色
  96.             sibling.color = BLACK;
  97.             //此时case3 已经被转换为 case4或者case5
  98.             fixDoubleBlack(x);
  99.             return;
  100.         }
  101.         //兄弟为黑
  102.         //两个侄子都为黑
  103.         if (sibling != null) {
  104.             if (isBlack(sibling.left) && isBlack(sibling.right)) {
  105.                 /*
  106.                  * case 4:被调整节点的兄弟为黑,两个侄于都为黑
  107.                  * 将兄弟变红, 目的是将删除节点和兄弟那边的黑色高度同时减少1
  108.                  * 如果父亲是红,则需将父亲变为黑,避免红红,此时路径黑节点数目不变
  109.                  * 如果父亲是黑,说明这条路径则少了一个黑,再次让父节点触发双黑
  110.                  * */
  111.                 //将兄弟变红, 目的是将删除节点和兄弟那边的黑色高度同时减少1
  112.                 sibling.color = RED;
  113.                 if (isRed(parent)) {
  114. //                    如果父亲是红,则需将父亲变为黑,避免红红,此时路径黑节点数目不变
  115.                     parent.color = BLACK;
  116.                 } else {
  117.                     //如果父亲是黑,说明这条路径则少了一个黑,再次让父节点触发双黑
  118.                     fixDoubleBlack(parent);
  119.                 }
  120.             } else {
  121.                 //CASE5 至少有一个侄子不是黑色
  122.                 /*
  123.                  *
  124.                  * case 5:被调整节点的兄弟为黑
  125.                  * 如果兄弟是左孩子,左侄子是红  LL 不平衡
  126.                  * 如果兄弟是左孩子,右侄子是红  LR 不平衡
  127.                  * 如果兄弟是右孩子,右侄于是红  RR 不平衡
  128.                  * 如果兄弟是右孩子,左侄于是红  RL 不平衡
  129.                  * */
  130.                 if(sibling.isLeftChild()&&isRed(sibling.left)){
  131.                     // 如果兄弟是左孩子,左侄子是红  LL 不平衡
  132.                     rotateRight(parent);
  133.                     //兄弟的做孩子变黑
  134.                     sibling.left.color=BLACK;
  135.                     //兄弟变成父亲的颜色
  136.                     sibling.color= parent.color;
  137.                     //父亲变黑
  138.                     parent.color=BLACK;
  139.                 }else if(sibling.isLeftChild()&&isRed(sibling.right)){
  140.                     //如果兄弟是左孩子,右侄子是红  LR 不平衡
  141.                     //变色必须在上 否则旋转后会空指针
  142.                     //兄弟的右孩子变为父节点颜色
  143.                     sibling.right.color= parent.color;
  144.                     //父节点变黑
  145.                     parent.color=BLACK;
  146.                     rotateLeft(sibling);
  147.                     rotateRight(parent);
  148.                 }
  149.             }
  150.         } else {
  151.             fixDoubleBlack(parent);
  152.         }
  153.     }
  154.     private void doRemove(Node deleted) {
  155.         Node replaced = findReplaced(deleted);
  156.         Node parent = deleted.parent;
  157.         if (replaced == null) {
  158.             //没有子节点
  159.             /* case1:删的是根节点,没有子节点
  160.              * 删完了,直接将 root=null
  161.              * */
  162.             if (deleted == root) {
  163.                 root = null;
  164.             } else {
  165.                 /*
  166.                  * Case2:删的是黑,剩下的是红剩下这个红节点变黑
  167.                  * */
  168.                 if (isBlack(deleted)) {
  169.                     //复杂处理,先调整平衡再删除
  170.                     fixDoubleBlack(deleted);
  171.                 } else {
  172.                     //红色不处理
  173.                 }
  174.                 //删除的不是根节点且没有孩子
  175.                 if (deleted.isLeftChild()) {
  176.                     parent.left = null;
  177.                 } else {
  178.                     parent.right = null;
  179.                 }
  180.                 deleted.parent = null;
  181.             }
  182.             return;
  183.         } else if (replaced.left == null || replaced.right == null) {
  184.             //有一个子节点
  185.             /* case1:删的是根节点,有一个子节点
  186.              * 用剩余节点替换了根节点的 key,Value,根节点孩子=null,颜色保持黑色 不变
  187.              * */
  188.             if (deleted == root) {
  189.                 root.key = replaced.key;
  190.                 root.value = replaced.value;
  191.                 root.left = root.right = null;
  192.             } else {
  193.                 //删除的不是根节点但是有一个孩子
  194.                 if (deleted.isLeftChild()) {
  195.                     parent.left = replaced;
  196.                 } else {
  197.                     parent.right = replaced;
  198.                 }
  199.                 replaced.parent = parent;
  200.                 deleted.right = deleted.left = deleted.parent = null;
  201.                 if (isBlack(deleted) && isBlack(replaced)) {
  202.                     //如果删除的是黑色剩下的也是黑色,需要复杂处理,先删除再平衡
  203.                     fixDoubleBlack(replaced);
  204.                 } else {
  205.                     /*
  206.                      * Case2:删的是黑,剩下的是红剩下这个红节点变黑
  207.                      * */
  208.                     replaced.color = BLACK;
  209.                 }
  210.             }
  211.             return;
  212.         } else {
  213.             //两个子节点
  214.             //交换删除节点和删除节点的后几点的key,value,这
  215.             // 样被删除节点就只有一个子节点或没有子节点了
  216.             int t = deleted.key;
  217.             deleted.key = replaced.key;
  218.             replaced.key = t;
  219.             Object v = deleted.value;
  220.             deleted.value = replaced.value;
  221.             replaced.value = v;
  222.             doRemove(replaced);
  223.             return;
  224.         }
  225.     }
  226.     private Node find(int key) {
  227.         Node p = root;
  228.         while (p != null) {
  229.             if (key > p.key) {
  230.                 //key更大向右找
  231.                 p = p.right;
  232.             } else if (key < p.key) {
  233.                 //向左找
  234.                 p = p.left;
  235.             } else {
  236.                 return p;
  237.             }
  238.         }
  239.         return null;
  240.     }
  241.     //查找删除后的剩余节点
  242.     private Node findReplaced(Node deleted) {
  243.         if (deleted.left == null & deleted.right == null) {
  244.             //没有子节点
  245.             return null;
  246.         } else if (deleted.left == null) {
  247.             return deleted.right;
  248.         } else if (deleted.right == null) {
  249.             return deleted.left;
  250.         } else {
  251.             Node s = deleted.right;
  252.             while (s != null) {
  253.                 //右子树的最小值
  254.                 s = s.left;
  255.             }
  256.             return s;
  257.         }
  258.     }
  259. }
复制代码
    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 四种失衡环境

  
  1. LL
  2.     -失衡节点的 bf >1,即左边更高
  3.     -失衡节点的左孩子的bf>=0即左孩子这边也是左边更高或等
  4.     一次右旋可以恢复平衡
  5. LR
  6.     -失衡节点的 bf >1,即左边更高
  7.     -失衡节点的左孩子的bf<0 即左孩子这边是右边更高
  8.     左子节点先左旋,将树修正为LL情况,
  9.     然后失衡节点再右旋,恢复平衡
  10. RL
  11.     -失衡节点的 bf <-1,即右边更高
  12.     -失衡节点的右孩子的bf>0,即右孩子这边左边更高
  13.     右子节点先右旋,将树修正为RR情况,
  14.     然后失衡节点再左旋,恢复平衡
  15. RR
  16.     -失衡节点的 bf<-1,即右边更高
  17.     -失衡节点的右孩子的bf<=0,即右孩子这边右边更高或等高
  18.     一次左旋可以恢复平衡
复制代码
   
  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;public class AVLTree {    static class AVLNode {        int key;        int height = 1;//高度初始值1        AVLNode left, right;        private AVLNode root;        Object value;        public AVLNode(int key, Object value) {            this.key = key;            this.value = value;        }        public AVLNode(int key, AVLNode left, AVLNode right, AVLNode root) {            this.key = key;            this.left = left;            this.right = right;            this.root = root;        }    }    //处理节点高度    private int haight(AVLNode node) {        return node == null ? 0 : node.height;    }    //增、删、旋转更新节点高度    //最大高度+1    public void updateHeight(AVLNode treeNode) {        treeNode.height = Integer.max(haight(treeNode.left), haight(treeNode.right)) + 1;    }    /*    平衡因子:一个节点左子树高度-右子树高度所得结果     小于1平衡:(0,1,-1)     大于1不平衡         >1:左边高         <-1:右边高     */    public int bf(AVLNode avlNode) {        return haight(avlNode.left) - haight(avlNode.right);    }    //四种失衡环境        /*        LL            -失衡节点的 bf >1,即左边更高            -失衡节点的左孩子的bf>=0即左孩子这边也是左边更高或等            一次右旋可以规复平衡        LR            -失衡节点的 bf >1,即左边更高            -失衡节点的左孩子的bf<0 即左孩子这边是右边更高            左子节点先左旋,将树修正为LL环境,            然后失衡节点再右旋,规复平衡        RL            -失衡节点的 bf <-1,即右边更高            -失衡节点的右孩子的bf>0,即右孩子这边左边更高            右子节点先右旋,将树修正为RR环境,            然后失衡节点再左旋,规复平衡        RR            -失衡节点的 bf<-1,即右边更高            -失衡节点的右孩子的bf<=0,即右孩子这边右边更高或等高            一次左旋可以规复平衡*/    //右旋    /**     * @Description 返回旋转后的节点     * @Param [avlNode] 必要旋转的节点     **/    private AVLNode rightRotate(AVLNode redNode) {        AVLNode yellowNode = redNode.left;        /*         *黄色节点有右子节点,给右子节点重新找父级节点         *由于二叉搜索树特性,某个节点的左子节点肯定小于 本身,右子节点肯定大于本身         * 故:yelllow的右子节点肯定大于yellow且小于rea,         *    所以,gree可以作为red的左子结点         * */        /*        AVLNode greeNode = yellowNode.right;        redNode.left = greeNode;        */        redNode.left = yellowNode.right;        yellowNode.right = redNode;        //更新高度,赤色和黄色都会改变        updateHeight(redNode);        updateHeight(yellowNode);        return yellowNode;    }    //左旋    private AVLNode leftRotate(AVLNode redNode) {        //左旋和右旋操作相反        AVLNode yellowNode = redNode.right;        //处理yellow的子节点        redNode.right = yellowNode.left;        //yellow变为跟,原red比yellow小,为yellow的left        yellowNode.left = redNode;        updateHeight(redNode);        updateHeight(yellowNode);        return yellowNode;    }    /*    * LR            -失衡节点的 bf >1,即左边更高            -失衡节点的左孩子的bf<0 即左孩子这边是右边更高            左子节点先左旋,将树修正为LL环境,            然后失衡节点再右旋,规复平衡    * */    //先左旋再右旋    private AVLNode leftRightRotate(AVLNode node) {        //修正左子结点LL        node.left = leftRotate(node.left);        return rightRotate(node);    }    /*    *   RL            -失衡节点的 bf <-1,即右边更高            -失衡节点的右孩子的bf>0,即右孩子这边左边更高            右子节点先右旋,将树修正为RR环境,            然后失衡节点再左旋,规复平衡    * */    //先右旋再左旋    private AVLNode rightLeftRotate(AVLNode node) {        //修正右子节点为RR        node.right = rightRotate(node.left);        return leftRotate(node);    }    //检查节点是否失衡,重新平衡
  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.     }    AVLNode root;    public void put(int key, Object value) {        doPut(root, key, value);    }    //找空位并添加新的节点    private AVLNode doPut(AVLNode node, int key, Object value) {        /*         * 1.找到空位,创建新节点         * 2.key 已存在 更新位置         * 3.继续寻找         *  */        //未找到        if (node == null) {            return new AVLNode(key, value);        }        //找到了节点 重新赋值        if (key == node.key) {            node.value = value;            return node;        }        //继续查找        if (key < node.key) {            //继续向左,并创建父子关系            node.left = doPut(node.left, key, value);        } else {            //向右找,并创建父子关系            node.right = doPut(node.right, key, value);        }        //更新节点高度        updateHeight(node);        //重新平衡树        return checkBalance(node);    }    //删除
  30.     public void remove(int key) {
  31.         root = doRemove(root, key);
  32.     }
  33.     private AVLNode doRemove(AVLNode node, int key) {
  34.         //1. node==null
  35.         if (node == null) {
  36.             return node;
  37.         }
  38.         //2.未找到key
  39.         if (key < node.key) {
  40.             //未找到key,且key小于当前节点key,继续向左
  41.             node.left = doRemove(node.left, key);
  42.         } else if (key > node.key) {
  43.             //向右找
  44.             node.right = doRemove(node.right, key);
  45.         } else {
  46.             //3.找到key
  47.             if (node.left == null && node.right == null) {
  48.                 //3.1 没有子节点
  49.                 return null;
  50.             } else if (node.left != null && node.right == null) {
  51.                 //3.2 一个子节点(左节点)
  52.                 node = node.left;
  53.             } else if (node.left == null && node.right != null) {
  54.                 //3.2 一个子节点(右节点)
  55.                 node = node.right;
  56.             } else {
  57.                 //3.3 两个子节点
  58.                 //找到他最小的后继节点,右子树向左找到底
  59.                 AVLNode s=node;
  60.                 while (s.left!=null){
  61.                     s=s.left;
  62.                 }
  63.                 //s即为后继节点,将节点删除并重新修正右子树
  64.                 s.right=doRemove(s.right,s.key);
  65.                 //左子树为s.left,右子树为原删除节点的左子树
  66.                 s.left=node.left;
  67.                 node=s;
  68.             }
  69.         }
  70.         //4.更新高度
  71.         updateHeight(node);
  72.         //5.检查是否失衡
  73.         return checkBalance(node);
  74.     }}
复制代码
   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;import static org.alogorithm.tree.RedBlackTree.Color.BLACK;import static org.alogorithm.tree.RedBlackTree.Color.RED;public class RedBlackTree {    enum Color {RED, BLACK}    private Node root;    private static class Node {        int key;        Object value;        Node left;        Node right;        Node parent;//父节点        Color color = RED;//颜色        public Node() {        }        public Node(int key, Object value) {            this.key = key;            this.value = value;        }        //是否是左孩子,左未true,右为false        boolean isLeftChild() {            return parent != null && this == parent.left;        }        //获取叔叔节点        Node uncle() {            //有父节点,和父节点的父节点才气有叔叔节点            if (parent == null || parent.parent == null) {                return null;            }            if (parent.isLeftChild()) {                //假如父亲为左子节点则返回右子节点,                return parent.parent.right;            } else {                //假如父亲为右子节点则返回左子节点                return parent.parent.left;            }        }        //获取兄弟节点        Node sibling() {            if (parent == null) {                return null;            }            if (this.isLeftChild()) {                return parent.right;            } else {                return parent.left;            }        }    }    //判定颜色    boolean isRed(Node node) {        return node != null && node.color == RED;    }    boolean isBlack(Node node) {        return node == null || node.color == BLACK;    }    //和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.     }    //新增或更新    void put(int key, Object value) {        Node p = root;        Node parent = null;        while (p != null) {            parent = p;            if (key < p.key) {                //向左找                p = p.left;            } else if (key > p.key) {                p = p.right;            } else {                //更新                p.value = value;                return;            }        }        //插入        Node interestNode = new Node(key, value);        //假如parent为空        if (parent == null) {            root = interestNode;        } else if (key < parent.key) {            parent.left = interestNode;            interestNode.parent = parent;        } else {            parent.right = interestNode;            interestNode.parent = parent;        }        fixRedRed(interestNode);    }    /*     * 1.所有节点都有两种颜色:红与黑     * 2.所有 null 视为玄色     * 3.赤色节点不能相邻     * 4.根节点是玄色     * 5.从根到任意一个叶子节点,路径中的玄色节点数一样(玄色完美平衡)     * */    //修复红红不平衡    void fixRedRed(Node x) {        /*         * 插入节点均视为赤色         * 插入节点的父亲为赤色         * 触发红红相邻         * case 3:叔叔为赤色         * case 4:叔叔为玄色         * */        //case 1:插入节点为根节点,将根节点变黑        if (x == root) {            x.color = BLACK;            return;        }        //case 2:插入节点的父亲若为玄色树的红黑性质不变,无需调整        if (isBlack(x.parent)) {            return;        }        Node parent = x.parent;        Node uncle = x.uncle();        Node grandParent = parent.parent;        //插入节点的父亲为赤色        if (isRed(uncle)) {            //红红相邻叔叔为赤色时(仅通过变色即可)            /*             * 为了包管玄色平衡,连带的叔叔也变为玄色·             * 祖父假如是玄色不变,会造成这颗子树玄色过多,因此祖父节点变为赤色祖父假如酿成赤色,             * 可能会接着触发红红相邻,因此对将祖父举行递归调整,祖父的父亲变为玄色             * */            parent.color = BLACK;            uncle.color = BLACK;            grandParent.color = RED;            fixRedRed(grandParent);            return;        } else {            //触发红红相邻叔叔为玄色            /*             * 1.父亲为左孩子,插入节点也是左孩子,此时即 LL不平衡(右旋一次)             * 2.父亲为左孩子,插入节点是右孩子,此时即 LR不平衡(父亲左旋,祖父右旋)             * 3.父亲为右孩子,插入节点也是右孩子,此时即 RR不平衡(左旋一次)             * 4.父亲为右孩子,插入节点是左孩子,此时即 RL不平衡(父亲右旋,祖父左旋)             *             */            if (parent.isLeftChild() && x.isLeftChild()) {                //假如父亲为左子节点,查询节点也为左子结点即为LL(祖父右旋处理)                //父节点变黑(和叔叔节点同为玄色)                parent.color = BLACK;                //祖父节点变红                grandParent.color = RED;                rotateRight(grandParent);            } else if (parent.isLeftChild() && !x.isLeftChild()) {                //parent为左子节点,插入节点为右子节点,LR(父亲左旋,祖父右旋)                rotateLeft(parent);                //插入节点变为玄色                x.color = BLACK;                //祖父变为赤色                grandParent.color = RED;                rotateRight(grandParent);            } else if (!parent.isLeftChild() && !x.isLeftChild()) {                //父节点变黑(和叔叔节点同为玄色)                parent.color = BLACK;                //祖父节点变红                grandParent.color = RED;                rotateLeft(grandParent);            } else if (!parent.isLeftChild() && x.isLeftChild()) {                rotateRight(parent);                //插入节点变为玄色                x.color = BLACK;                //祖父变为赤色                grandParent.color = RED;                rotateLeft(grandParent);            }        }    }    //删除
  57.     /*
  58.      * 删除
  59.      * 正常删、会用到李代桃僵技巧、遇到黑黑不平衡进行调整
  60.      * */
  61.     public void remove(int key) {
  62.         Node deleted = find(key);
  63.         if (deleted == null) {
  64.             return;
  65.         }
  66.         doRemove(deleted);
  67.     }
  68.     //检测双黑节点删除
  69.     /*
  70.      *
  71.      * 删除节点和剩下节点都是黑触发双黑,双黑意思是,少了一个黑
  72.      * case 3:删除节点或剩余节点的兄弟为红此时两个侄子定为黑
  73.      * case 4:删除节点或剩余节点的兄弟、和兄弟孩子都为黑
  74.      * case 5:删除节点的兄弟为黑,至少一个红侄子
  75.      *
  76.      * */
  77.     private void fixDoubleBlack(Node x) {
  78.         //把case3处理为case4和case5
  79.         if (x == root) {
  80.             return;
  81.         }
  82.         Node parent = x.parent;
  83.         Node sibling = x.sibling();
  84.         if (sibling.color == RED) {
  85.             //进入case3
  86.             if (x.isLeftChild()) {
  87.                 //如果是做孩子就进行左旋
  88.                 rotateLeft(parent);
  89.             } else {
  90.                 //如果是右孩子就进行右旋
  91.                 rotateRight(parent);
  92.             }
  93.             //父亲颜色变为红色(父亲变色前肯定为黑色)
  94.             parent.color = RED;
  95.             //兄弟变为黑色
  96.             sibling.color = BLACK;
  97.             //此时case3 已经被转换为 case4或者case5
  98.             fixDoubleBlack(x);
  99.             return;
  100.         }
  101.         //兄弟为黑
  102.         //两个侄子都为黑
  103.         if (sibling != null) {
  104.             if (isBlack(sibling.left) && isBlack(sibling.right)) {
  105.                 /*
  106.                  * case 4:被调整节点的兄弟为黑,两个侄于都为黑
  107.                  * 将兄弟变红, 目的是将删除节点和兄弟那边的黑色高度同时减少1
  108.                  * 如果父亲是红,则需将父亲变为黑,避免红红,此时路径黑节点数目不变
  109.                  * 如果父亲是黑,说明这条路径则少了一个黑,再次让父节点触发双黑
  110.                  * */
  111.                 //将兄弟变红, 目的是将删除节点和兄弟那边的黑色高度同时减少1
  112.                 sibling.color = RED;
  113.                 if (isRed(parent)) {
  114. //                    如果父亲是红,则需将父亲变为黑,避免红红,此时路径黑节点数目不变
  115.                     parent.color = BLACK;
  116.                 } else {
  117.                     //如果父亲是黑,说明这条路径则少了一个黑,再次让父节点触发双黑
  118.                     fixDoubleBlack(parent);
  119.                 }
  120.             } else {
  121.                 //CASE5 至少有一个侄子不是黑色
  122.                 /*
  123.                  *
  124.                  * case 5:被调整节点的兄弟为黑
  125.                  * 如果兄弟是左孩子,左侄子是红  LL 不平衡
  126.                  * 如果兄弟是左孩子,右侄子是红  LR 不平衡
  127.                  * 如果兄弟是右孩子,右侄于是红  RR 不平衡
  128.                  * 如果兄弟是右孩子,左侄于是红  RL 不平衡
  129.                  * */
  130.                 if(sibling.isLeftChild()&&isRed(sibling.left)){
  131.                     // 如果兄弟是左孩子,左侄子是红  LL 不平衡
  132.                     rotateRight(parent);
  133.                     //兄弟的做孩子变黑
  134.                     sibling.left.color=BLACK;
  135.                     //兄弟变成父亲的颜色
  136.                     sibling.color= parent.color;
  137.                     //父亲变黑
  138.                     parent.color=BLACK;
  139.                 }else if(sibling.isLeftChild()&&isRed(sibling.right)){
  140.                     //如果兄弟是左孩子,右侄子是红  LR 不平衡
  141.                     //变色必须在上 否则旋转后会空指针
  142.                     //兄弟的右孩子变为父节点颜色
  143.                     sibling.right.color= parent.color;
  144.                     //父节点变黑
  145.                     parent.color=BLACK;
  146.                     rotateLeft(sibling);
  147.                     rotateRight(parent);
  148.                 }
  149.             }
  150.         } else {
  151.             fixDoubleBlack(parent);
  152.         }
  153.     }
  154.     private void doRemove(Node deleted) {
  155.         Node replaced = findReplaced(deleted);
  156.         Node parent = deleted.parent;
  157.         if (replaced == null) {
  158.             //没有子节点
  159.             /* case1:删的是根节点,没有子节点
  160.              * 删完了,直接将 root=null
  161.              * */
  162.             if (deleted == root) {
  163.                 root = null;
  164.             } else {
  165.                 /*
  166.                  * Case2:删的是黑,剩下的是红剩下这个红节点变黑
  167.                  * */
  168.                 if (isBlack(deleted)) {
  169.                     //复杂处理,先调整平衡再删除
  170.                     fixDoubleBlack(deleted);
  171.                 } else {
  172.                     //红色不处理
  173.                 }
  174.                 //删除的不是根节点且没有孩子
  175.                 if (deleted.isLeftChild()) {
  176.                     parent.left = null;
  177.                 } else {
  178.                     parent.right = null;
  179.                 }
  180.                 deleted.parent = null;
  181.             }
  182.             return;
  183.         } else if (replaced.left == null || replaced.right == null) {
  184.             //有一个子节点
  185.             /* case1:删的是根节点,有一个子节点
  186.              * 用剩余节点替换了根节点的 key,Value,根节点孩子=null,颜色保持黑色 不变
  187.              * */
  188.             if (deleted == root) {
  189.                 root.key = replaced.key;
  190.                 root.value = replaced.value;
  191.                 root.left = root.right = null;
  192.             } else {
  193.                 //删除的不是根节点但是有一个孩子
  194.                 if (deleted.isLeftChild()) {
  195.                     parent.left = replaced;
  196.                 } else {
  197.                     parent.right = replaced;
  198.                 }
  199.                 replaced.parent = parent;
  200.                 deleted.right = deleted.left = deleted.parent = null;
  201.                 if (isBlack(deleted) && isBlack(replaced)) {
  202.                     //如果删除的是黑色剩下的也是黑色,需要复杂处理,先删除再平衡
  203.                     fixDoubleBlack(replaced);
  204.                 } else {
  205.                     /*
  206.                      * Case2:删的是黑,剩下的是红剩下这个红节点变黑
  207.                      * */
  208.                     replaced.color = BLACK;
  209.                 }
  210.             }
  211.             return;
  212.         } else {
  213.             //两个子节点
  214.             //交换删除节点和删除节点的后几点的key,value,这
  215.             // 样被删除节点就只有一个子节点或没有子节点了
  216.             int t = deleted.key;
  217.             deleted.key = replaced.key;
  218.             replaced.key = t;
  219.             Object v = deleted.value;
  220.             deleted.value = replaced.value;
  221.             replaced.value = v;
  222.             doRemove(replaced);
  223.             return;
  224.         }
  225.     }
  226.     private Node find(int key) {
  227.         Node p = root;
  228.         while (p != null) {
  229.             if (key > p.key) {
  230.                 //key更大向右找
  231.                 p = p.right;
  232.             } else if (key < p.key) {
  233.                 //向左找
  234.                 p = p.left;
  235.             } else {
  236.                 return p;
  237.             }
  238.         }
  239.         return null;
  240.     }
  241.     //查找删除后的剩余节点
  242.     private Node findReplaced(Node deleted) {
  243.         if (deleted.left == null & deleted.right == null) {
  244.             //没有子节点
  245.             return null;
  246.         } else if (deleted.left == null) {
  247.             return deleted.right;
  248.         } else if (deleted.right == null) {
  249.             return deleted.left;
  250.         } else {
  251.             Node s = deleted.right;
  252.             while (s != null) {
  253.                 //右子树的最小值
  254.                 s = s.left;
  255.             }
  256.             return s;
  257.         }
  258.     }
  259. }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

钜形不锈钢水箱

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表