Lecture11

2021-04-10  本文已影响0人  不到7不改名

Binary Search Tree

Full vs. Complete Binary Trees

image-20210409124544762.png image-20210409125055015.png

Complete vs. Incomplete Tree

image-20210409125438993.png image-20210409125638196.png

Terminology: Tree Height

image-20210409125919886.png

Tree Size: Full Tree

image-20210409130539079.png

Tree Height = f(Tree size)

image-20210409130759184.png

BST Operations: Best / Worst Case

image-20210409185533622.png

Binary Trees: Underlying Structure

Tree as Arrays: Structure

image-20210409190040254.png
image-20210409190151498.png

Tree as Arrays: Indexing

image-20210409190241066.png

Abstract Data Type: Heap

Heap

Binary Search Tree vs. Heap

image-20210409221006261.png

MaxHeap vs. MinHeap

image-20210409221414323.png image-20210409221754560.png

Invalid Heaps

image-20210409222239012.png image-20210409222530554.png

Heap: Subtrees are Heaps

Heap property: both left and right subtrees must also be a heap.

image-20210409223318753.png

Heap: Single-node Trees are Heaps

Heap property: single-node trees are valid heaps.

image-20210409223508844.png

Heap: add(Element/Key)

Step1: A valid MaxHeap prior to adding a new node. New node location.

image-20210409231211399.png

Step2: Heap property temporarily violated!

Step3: Swap Parent and Child elements to restore MaxHeap property

Step4: Swap Parent and Child elements AGAIN to restore MaxHeap property

Step5: Now MaxHeap property is violated one level up

Step6: MaxHeap property is restored. Heap is valid

image-20210409231304026.png

Heap: top()

Step1: top(max in this case) element(10) is to be removed

Step2: top is removed, there will be a gap. Let's "fill/swap it" with the "last element"

image-20210409232256244.png

Step3: Now MaxHeap property is violated

Step4: Parent and LARGEST KEY(9) child elements to restore MaxHeap property

image-20210409232413275.png

Step5: MaxHeap property is restored. Heap is valid

Heap: peek()

Step 1: retrieve the top element without removing it.

image-20210410102901149.png

Application: Heap Sort

heapSort(Collection c){
    if(c !=null){
    
        Heap h = new Heap();
        List out = new List();
        
        while(!h.isEmpty()){
            out.add(h.top());
        }
    }
    return out;
}
image-20210410103602136.png

Application: TOP K Elements

topK(Collection c, int k){
    if(c != null & k>0){
        int count = 0;
        Heap h = new Heap();
        List out = new List();
        
        while( !h.isEmpty()){
            out.add(h.top());
            count++;
            if(count > k) break;
        }
    }
    return out;
}
image-20210410104205194.png

Abstract Data Type: Priority Queue

上一篇 下一篇

猜你喜欢

热点阅读