Chapter 14: Binary Search Trees

前言

二元搜尋樹是一個相當厲害的資料結構,在尋找,插入,刪除的平均時間複雜度為O(log n),相對其他線性的資料結構都快上很多。

大綱

  • Case study: array vs. BST

    • Lookup

    • Insertion

    • Removal

  • Implementation

    • Inserting elements

    • Finding elements

    • Optimizing contains

    • Removing elements

      • Case 1: Leaf node

      • Case 2: Nodes with one child

      • Case 3: Nodes with two children

      • Implementation

Case study: array vs. BST

先來討論一下array和BST的差異,以下面case為例

  • Lookup

    • 對於一個unsorted array只能一一尋找所需要的元素

      • That’s why array.contains(:) is an O(n) operation.

    • 對於一顆平衡的BST, 每次的尋找都可以排除一半其他不可能的元素,其複雜度為O(log n)

  • Insertion

    • 每次插入元素都array中,都會造成被插入位置的後方元素進行位移的動作

      • In the above example, zero is inserted in front of the array, causing all other elements to shift backwards by one position. Inserting into an array has a time complexity of O(n).

    • 對於BST找到對應插入位置只需要O(log n)

    • Removing an element from a BST is still an O(log n) operation.

Inserting elements

  • 對於一顆BST的定義

    • leftChild.vale < root.value

    • rightChild.value >= root.value

Finding elements

  • 透過traverseInOrder來找element,並沒有好好活用到BST的特性。

Optimizing contains

  • 活用BST特性,不用每個element都要走過。

Removing elements

  • 刪除元素,對BST是比較複雜的,有下列種case要討論

    • Case 1: Leaf node

      • 被刪除的節點是葉子,這個好處理就直接刪除

    • Case 2: Nodes with one child

      • 被刪除的節點有一個child, 那需要處理這個child,但也很簡單,就是把這個child連接到阿公節點。

    • Case 3: Nodes with two children

      • 被刪除的節點有兩個child, 處理方式就是拿右子樹的最小值來當root,當然也可以拿左子樹的最大值來當root。

Last updated