1125助教課

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 17

BINARY SEARCH TREE

11/25 助教課

1
定義
• 二元搜尋樹( binary search tree )可以是空集

• 假使不是空集合,則樹中的每一節點均含有一鍵
值 (key value) ,且具有下列性質:
• 在左子樹的所有鍵值均小於樹根的鍵值。
• 在右子樹的所有鍵值均大於樹根的鍵值。
• 左子樹和右子樹亦是二元搜尋樹。
• 中序遊走一個 binary search tree 所產生的 sear
ch key value 序列是由小至大排列。
• 最小節點:從樹根開始往左 children 走到底。
• 最大節點:從樹根開始往右 children 走到底。

2
INSERTION

• 二元搜尋的加入很簡單,因二元搜尋樹的性質是
左子樹的鍵值均小於樹根的鍵值,而右子樹的鍵
值均大於樹根的鍵值。
• 加入某一鍵值只要逐一比較,依鍵值的大小往右
或往左,即可找到此鍵值欲加入的適當位置

3
其演算的程序及步驟如下:

1. 一次讀入一個數字,直到輸入結束。
2. 如果是空樹,則新節點即為根節點。
3. 如果不是空樹,將新節點資料與根節點比
較,如果比較小的話,則往左子樹,否則
往右子樹。
4. 重複步驟3,直到空指標為止。
5. 將新節點加到最後停留之處。

4
PSEUDOCODE
TREE-INSERT(T, z)
y ← NIL
x ← root[T ]
while x ≠ NIL
do y ← x
if key[z] < key[x]
then x ← left[x]
else x ← right[x]
p[z] ← y
if y = NIL // T was empty
then root[T ] ← z
else if key[z] < key[y]
then left[y] ← z
else right[y]← z

5
【範例】假設有一棵二元搜尋樹如下

50

40 65

60
30 45

6
若欲加入 48
 依上述規則加在鍵值 45 的右邊
 因為 48 比 50 小,故往左邊
 但比 40 大往右邊
 最後又比 45 大,故加在 45 的右邊。
50

40 65

30 45 60

48

7
若繼續加入 90 則為
50

65
40

45 60 90
30

48

8
練習 -INSERTION

按照以下順序繪製新的 BST
(1) Insert 20
(2) Insert 1 10
(3) Insert 7

5 15

2 8 13 19

9
練習 -INSERTION
(1) Insert 20

10

5 15

2 8 13 19

6 20

10
練習 -INSERTION
(2) Insert 1

10

5 15

2 8 13 19

1 6 20

11
練習 -INSERTION
(3) Insert 7 10

5 15

2 8 13 19

1 6 20

12
INORDER-TREE-WALK

Inorder (Left, Root, Right) : 4 2 5 1 3

13
練習 - INORDER-TREE-WALK

14
練習 - INORDER-TREE-WALK

ANS:
K, G, D, L, H, M, B, A, E, C

15
INORDER-TREE-WALK

Print keys in a binary search tree in order, recursively


- Check to make sure that x is not NIL
- Recursively, print the keys of the nodes in x’s left subtree
- Print x’s key
- Recursively, print the keys of the nodes in x’s right subtree

5
INORDER-TREE-WALK(x)
if x ≠ NIL 3 7
then INORDER-TREE-WALK(left[x])
2 5 8
print key[x]
INORDER-TREE-WALK(right[x])

e.g. ABDFHK

16
參考資料

• https://www.geeksforgeeks.org/binary-search-tree
-set-1-search-and-insertion/
• http://www.csie.ntnu.edu.tw/~u91029/Order.html

17

You might also like