download

Matakuliah
Tahun
Versi
: T0026/Struktur Data
: 2005
: 1/1
Pertemuan 12
Binary Search Tree
1
Learning Outcomes
Pada akhir pertemuan ini, diharapkan mahasiswa
akan mampu :
• Mahasiswa dapat menghasilkan program
modular untuk mengimplementasikan
binary search tree
2
Outline Materi
•
•
•
•
•
Pengertian Binary search tree
Contoh Binary search tree
inserting data dalam binary search tree
deleting data dalam binary search tree
contoh program implementasi
3
Binary Search Tree (BST)
Binary Search Tree (BST) is Binary Tree that hasthe following properties :
–
Every element has a key, and no elements have the same key.
–
The key in a nonempty left subtree must be smaller than the key in the root of
subtree.
–
The key in a nonempty right subtree must be larger than the key in the root of
subtree.
–
The left and right subtrees are also BST.
Benefit :
BST has better performance in Insertion, Deletion, Searching.
Searching :
1. Start from the rot node.
2. If the key is equal, searching is terminated. Otherwise,compare with the root’s key
:
a. If the key is less than root’s key then move to Left Subtree
b. If the key is larger than root’s key then move to Right Subtree
54
30
20
35
70
60
Binary Search Tree
4
Operation on Binary Search Tree
•
Insert
54
54
54
70
70
60
Insert(54)
Insert(70)
Insert(60)
5
Operation on Binary Search Tree
•
Delete
•
•
•
Leaf as target node, no replacing for target node.
Non Leaf node and target node has single child, the child
replaces target node
Non Leaf node and target node has many descendants, target
node will be replaced by one of elements from :
•
Left subtree that has largest element.
•
Right subtree that has smallest element.
54
54
30
20
35
70
60
30
20
35
70
60
65
Before Delete(65)
After Delete(65)
6
Operation on Binary Search Tree
54
54
30
20
35
30
70
20
60
35
70
65
65
After Delete(60)
Before Delete(60)
35
30
20
54
70
60
65
After Delete(54)
30
20
35
60
70
60
30
20
35
70
65
65
Before Delete(54)
After Delete(54)
7