Download presentation
Presentation is loading. Please wait.
Published byYohanes Setiabudi Modified over 5 years ago
1
Binary Search Trees Chapter 9 2/24/2019 B.Ramamurthy
2
Binary Search Trees A binary tree that is built such that
every node's left subtree has key values less than the node's key value, and the node’s right subtree has key values greater than the node’s key value. A new node is added as a leaf. Above is NIST’s (National Institute of Standards and Technology) definition We will add a constraint that the key will be unique. 2/24/2019 B.Ramamurthy
3
Binary Search Tree We will define the operations of binary search tree. We will use the simple binary tree that we designed earlier. The semantics of the operation are loosely based on Chapter 9’s discussion on binary search trees. 2/24/2019 B.Ramamurthy
4
BST server side 2/24/2019 B.Ramamurthy
5
BST Client side 2/24/2019 B.Ramamurthy
6
2/24/2019 B.Ramamurthy
7
Insert, and Search methods
Insert (key, element) (Non_empty tree) Locate position (cursor) to insert. This will be parent of new node (key-element pair) to be inserted. 1.1 If key < cursor’s key, insert as left leaf 1.2 Else if key >cursor’s key, insert as right leaf 1.3 Else replace value of element with new value. (Empty tree) Create a tree with node with an item made up of key,element. 2/24/2019 B.Ramamurthy
8
Search(key) Locate the node with the given key.
1.1 If one exists return element of the node 1.2 Else return null. Both insert and search method use a utility method boolean locate(Key k, Btree b) That return true, if key is found and sets a cursor to the location where it was found. Returns false if not found, cursor has the location of parent for insert. 2/24/2019 B.Ramamurthy
9
Object remove(Comparable key)
Empty case: throw exception NonEmpty case: locate the key in the tree found key at cursor: 2.1 Left sub tree of cursor empty: set the cursor’s parent’s left or right sub tree with cursor’s right sub tree. 2.2 Left sub tree nonempty; right sub tree empty or non empty: 2.2.1 find the rightmost node; 2.2.2 replace cursor data with rightmost node’s data 2.2.3 remove rightmost node; return Item found at the node; Not found: Throw exception 2/24/2019 B.Ramamurthy
10
Examples Lets look at some representative examples using the animation tool. 2/24/2019 B.Ramamurthy
11
2/24/2019 B.Ramamurthy
12
2/24/2019 B.Ramamurthy
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.