> For the complete documentation index, see [llms.txt](https://garychang.gitbook.io/data-structure/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://garychang.gitbook.io/data-structure/lecture2-tree-and-binary-tree/lecture-2.8-advanced-trees/2.8.1-max-min-heap.md).

# 2.8.1 - Min-Max Heap

### 1. 定義

是一個Complete Binary Tree且滿足:

1. 此樹的level是以min-level與max-level交替出現
2. Root位於min-level
3. 若x位於min-level，則表示以x為root的子樹中，x是最小值，反之亦然

### 2. 運作

#### 2.1 insert x in a max-min heap

1. 將x放到最後一個節點的下一個位置
2. 考慮x的父點位於max/min level:
   1. max: 如果x比祖父點大，則x和祖父點交換，並往上驗證
   2. min: 如果x比祖父點小，則x和祖父點交換，並往上驗證

#### 2.2  delete min in a max-min heap

1. 移走root取得min
2. 將最後一個節點x刪除
3. 將x插入原本的root中
   1. 若root無子點，則結束
   2. 若root子孫中的最小值k是root的左右子點的其中一個，如果x>k則交換位置
   3. 若root子孫中的最小值k是root的子孫中的一個，k的父點p，如果x>k，則交換位置，接著x和p比較，若x>p則互換位置，並重複第三步
