Docsity

Binary search trees - OBJECT-ORIENTED PROGRAMME | CMSC 132, Study notes of Computer Science

Partial preview of the text

Download Binary search trees - OBJECT-ORIENTED PROGRAMME | CMSC 132 and more Study notes Computer Science in PDF only on Docsity!

Binary Search Trees

CMSC 132

Department of Computer ScienceUniversity of Maryland, College Park

Overview

Binary Search Tree Search Properties Construction Insertion Deletion Polymorphic BST Polymorphic, recursive linked list

Binary Search Trees

Examples

Binarysearch trees

Non-binarysearch tree

Iterative Search of BST

Node Find( Node n, Value

key

while (n != null) {^ if (n.data ==

key

)^

// Found it

return n; if (n.data >

key

)^

// In left subtree

n = n.left; else^

// In right subtree

n = n.right;

} return null; } Find( root, keyValue );

Example Binary Searches

Find ( 2 )^105

10 > 2, left5 > 2, left2 = 2, found

5 > 2, left2 = 2, found

Example Binary Searches

Find ( 25 )^105

10 < 25, right30 > 25, left25 = 25, found

5 < 25, right45 > 25, left30 > 25, left10 < 25, right25 = 25, found

Binary Search Tree Construction How to build & maintain binary trees?^ Insertion^ Deletion Maintain key property (invariant)^ Smaller values in left subtree^ Larger values in right subtree

Binary Search Tree – Insertion Algorithm 1. Perform search for value X 2. Search will end at node Y (if X not in tree) 3. If X < Y, insert new leaf X as new left subtree for Y 4. If X > Y, insert new leaf X as new right subtree for Y Observations O( log(n) ) operation for balanced tree Insertions may unbalance tree

Binary Search Tree – Deletion Algorithm 1. Perform search for value X 2. If X is a leaf, delete X 3. Else^

// must delete internal node a) Replace with largest value Y on left subtree

OR^ smallest value Z on right subtree b)^ Delete

replacement value (Y or Z) from subtree

Observation^ O( log(n) ) operation for balanced tree^ Deletions may unbalance tree

Example Deletion (Leaf)

Delete ( 25 )^105

10 < 25, right30 > 25, left25 = 25, delete 45

Example Deletion (Internal Node) Delete ( 10 )^105

Replacing 10with^

smallest value in rightsubtree

Deleting leaf

Resulting tree

BST Traversal Examples

Pre-order^ 44, 17, 32, 78,50, 48, 62, 88 In-order^ 17, 32, 44, 48,50, 62, 78, 88

88

44 17

78

32

(^5048)

62

Binary search tree

Sortedorder!

Post-order^ 32, 17, 48, 62,50, 88, 78, 44 Breadth-first^ 44, 17, 78, 32,50, 88, 48, 62

Polymorphic Binary Search Trees What do we mean by polymorphic?^ Implement two subtypes of Tree: EmptyTreeand NonEmptyTree^ We use EmptyTree, rather than null torepresent the empty tree^ Invoke methods on tree nodes, get empty ornonempty functionality

Recursive, Polymorphic Linked Lists^ Let’s see code for linked lists that uses thesame concept used for polymorphic trees^ Keys are kept in sorted order^ Have an interface List, and subtypes EmptyListand NonEmptyList^ See code distribution