2.4 - Binary Search Tree

二元搜尋樹介紹及相關演算法

1. 定義

  • 是一個binary tree,可以為空

  • left-children < root

  • right-children > root

  • left-children和right-children都是binary search tree

     10
    /  \
   5   12
  / \    \
 3   8    15
         /
        14

2. 相關演算法

2.1 在二元搜尋樹中尋找x

  1. 若b是空樹,搜尋失敗。

  2. 若x等於b的根節點的資料域之值,尋找成功。

  3. 若x小於b的根節點的資料域之值,搜尋左子樹。

  4. 若x大於b的根節點的資料域之值,尋找右子樹。

時間複雜度分析:

  1. worst case: O(n) in skewed binary tree

  2. best case: O(logn) in complete/full binary tree

2.2 在二元搜尋樹中刪除節點x

  1. 在BST中尋找x的位置

  2. 如果x是leaf,直接刪除

  3. 如果x是degree為1的節點

    1. 刪除x

    2. 將x的父點指向x的pointer指向x的子點

  4. 如果x是degree為2的節點

    1. 找到x的左子樹中的最大值/右子樹中的最小值y

    2. y回到step2/step3

2.3 在二元搜尋樹中加入節點x

  1. 若是空樹,則將x作為root插入

  2. 若x小於根節點,則把x插入到左子樹中

  3. 若x大於根節點,則把x插入到右子樹中(新插入節點總是在leaf)

Last updated