2020-11-16 树

2020-11-19  本文已影响0人  宇宙区长李小无

树的基本概念

树是n个节点组成的有限集,n为0,则称为空树。非空树有以下特点:

其他概念

二叉树

这棵树的节点最多只有2个子节点,也可能为0或1。

两种特殊形态
表现形式

可以得出:

二叉树的应用:


这时就需要二叉树的自平衡了,具体红黑树、AVL树、树堆可以实现。

二叉树的遍历

二叉堆

什么是二叉堆
二叉堆的自我调整

二叉堆的存储是顺序存储,也就是存储在数组中,通过完全二叉树的索引计算公式,知道一个父节点的索引,就能得出其左右子节点的索引,反之亦然。

优先队列

以实现最大堆为例,代码如下:

 class PriorityQueue {
  array: number[] = [];

  public enQueue(item: number) {
    this.array.push(item);
    this.upAdjust();
  }
  public deQueue() {
    this.array[0] = this.array[this.array.length - 1];
    this.array.pop();
    this.downAdjust();
  }

  public downAdjust() {
    const size = this.array.length;
    if (size == 0) {
      return;
    }
    let parentIndex = 0;
    const target = this.array[parentIndex];
    // 最大堆应该寻找左右子节点中的较大的一方进行位置交换
    // 先左
    let childIndex = parentIndex * 2 + 1;
    while (childIndex < size) {
      // 右子节点存在,且大于左子节点
      if (childIndex + 1 < size && this.array[childIndex+1] > this.array[childIndex]) {
        childIndex += 1;
      }
      if (target >= this.array[childIndex]) {
        break;
      }
      this.array[parentIndex] = this.array[childIndex];
      parentIndex = childIndex;
      // 还是默认先左子节点
      childIndex = parentIndex * 2 + 1;
    }
    this.array[parentIndex] = target;
  }
  public upAdjust() {
    const size = this.array.length;
    let childIndex = size - 1;
    // 只有一个元素
    if (childIndex == 0) {
      return;
    }
    // 目标元素
    const target = this.array[childIndex];
    let parentIndex = Math.floor((childIndex - 1) / 2);
    while (childIndex > 0 && target > this.array[parentIndex]) {
      this.array[childIndex] = this.array[parentIndex];
      childIndex = parentIndex;
      parentIndex = Math.floor((childIndex - 1) / 2);
    }
    this.array[childIndex] = target;
  }

}

function main() {
  const queue: PriorityQueue = new PriorityQueue();
  queue.enQueue(3);
  queue.enQueue(5);
  queue.enQueue(10); 
  queue.enQueue(2);
  queue.enQueue(2);
  queue.enQueue(9);
  queue.enQueue(7);
  console.log(queue.array);
  queue.deQueue();
  console.log(queue.array);
  queue.deQueue();
  console.log(queue.array);
}
main();

输出结果:


image.png
上一篇 下一篇

猜你喜欢

热点阅读