6.3 63
INTRODUCTION 6.3.1 6.3.2 6.3.3 6.3.4 634 6.3.5 6.3.6 What is Binary Search Tree? y Advantages Building Binary Search Tree Binary Search Tree Traversal Binary Search Tree Implementation Binary Search Tree Application 6.3.6.1 Primitive D t t 6 3 6 1 P i iti Data type 6.3.6.2 Abstract Data Type (ADT)
Building BST
BST characteristics : All nodes in LEFT sub tree are < ROOT node All nodes in RIGHT sub tree are >= ROOT node Usually data is unique (no duplicated data) INORDER traversal on BST will give data in ascending order. PREORDER or POSTORDER traversal will give data in different order. Any type of data can be stored in BST. y ype o da a ca s o ed S .
Intersession May 2009 UiTMT (MP, EZ, NIK) 4
3 4
-1 -3
Depth: 4 Leaves: 4
I D
Depth: 4 Leaves: 2
Compaq
Samsung
Apple pp
Dell
Toshiba
Depth: 2 Leaves: 3
Intersession May 2009 UiTMT (MP, EZ, NIK) 7
BST Traversal
Example (a) : Data : 5 6 1 3 7 9 2 -1 0 4 -3
5 1 0 6 7 9
3 4
-1 -3
I D
Compaq
Samsung
Apple
Dell
Toshiba
Inorder: Apple, Compaq, Dell, Hitachi, Samsung, Toshiba Preorder: Hitachi, Compaq, Apple, Dell, Samsung, Toshiba Postorder: Apple, Dell, Compaq, Toshiba, Samsung, Hitachi
10
BST Implementation
How to implement BST Data Structure? dynamic storage space. BST uses d i t BST ADT has to be modified to suit the type of data to be stored. ADT cant be common because data has to be compared can t to locate proper position. BST uses recursion method/technique. i th d/t h i
11
node
left
data
right
12
13
public int calcSize() private int calcSizeAll(node) p public double calcSum() () private double calcSumAll(node) public int countVal(value) private int countValAll(node, value) public void printCat() private void printCatAll(node, category) etc
14
// constructor : initialize data to d and make this as a leaf node public TreeNode(int d) { data = d; ; left=right = null; }
15
16
18
19
20
21
22
23
24
25
26
27
29
34
35
36
37
38