1 Trees 3: The Binary Search Tree Reading: Sections 4.3 and 4.6.

Slides:



Advertisements
Similar presentations
Binary Search Tree Smt Genap
Advertisements

DATA STRUCTURES AND ALGORITHMS Lecture Notes 9 Prepared by İnanç TAHRALI.
IKI 10100: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100: Lecture20.
IKI 10100I: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100I: Data.
Binary Search Trees Azhar Maqsood School of Electrical Engineering and Computer Sciences (SEECS-NUST)
1 Jake’s Pizza Shop Owner Jake Manager Chef Brad Carol Waitress Waiter Cook Helper Joyce Chris Max Len.
Binary Trees, Binary Search Trees COMP171 Fall 2006.
Trees, Binary Trees, and Binary Search Trees COMP171.
Trees, Binary Trees, and Binary Search Trees. 2 Trees * Linear access time of linked lists is prohibitive n Does there exist any simple data structure.
Review: Search Linear Search Binary Search Search demos: – ndan/dsal/appldsal.htmlhttp://
TCSS 342 BST v1.01 BST addElement To addElement(), we essentially do a find( ). When we reach a null pointer, we create a new node there. void addElement(Object.
1 BST Trees A binary search tree is a binary tree in which every node satisfies the following: the key of every node in the left subtree is.
1 Joe Meehean.  Important and common problem  Given a collection, determine whether value v is a member  Common variation given a collection of unique.
1 Trees 3: The Binary Search Tree Section Binary Search Tree A binary tree B is called a binary search tree iff: –There is an order relation
CS 146: Data Structures and Algorithms June 18 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
Binary Search Trees. BST Properties Have all properties of binary tree Items in left subtree are smaller than items in any node Items in right subtree.
Lecture Objectives  To learn how to use a tree to represent a hierarchical organization of information  To learn how to use recursion to process trees.
Recursion Bryce Boe 2013/11/18 CS24, Fall Outline Wednesday Recap Lab 7 Iterative Solution Recursion Binary Tree Traversals Lab 7 Recursive Solution.
Tree. Basic characteristic Top node = root Left and right subtree Node 1 is a parent of node 2,5,6. –Node 2 is a parent of node.
Trees Basic concepts of trees Implementation of trees Traversals of trees Binary trees Binary search trees AVL trees B-trees.
INTRODUCTION TO BINARY TREES P SORTING  Review of Linear Search: –again, begin with first element and search through list until finding element,
CMSC 341 Introduction to Trees. 8/3/2007 UMBC CMSC 341 TreeIntro 2 Tree ADT Tree definition  A tree is a set of nodes which may be empty  If not empty,
DATA STRUCTURES AND ALGORITHMS Lecture Notes 5 Prepared by İnanç TAHRALI.
BINARY SEARCH TREE. Binary Trees A binary tree is a tree in which no node can have more than two children. In this case we can keep direct links to the.
Binary Search Trees Binary Search Trees (BST)  the tree from the previous slide is a special kind of binary tree called a binary.
1 Chapter 10 Trees. 2 Definition of Tree A tree is a set of linked nodes, such that there is one and only one path from a unique node (called the root.
Trees, Binary Trees, and Binary Search Trees COMP171.
Lec 15 Oct 18 Binary Search Trees (Chapter 5 of text)
CS 202, Spring 2003 Fundamental Structures of Computer Science II Bilkent University1 Trees CS 202 – Fundamental Structures of Computer Science II Bilkent.
Trees 2: Section 4.2 and 4.3 Binary trees. Binary Trees Definition: A binary tree is a rooted tree in which no vertex has more than two children
CMSC 341 Introduction to Trees. 2/21/20062 Tree ADT Tree definition –A tree is a set of nodes which may be empty –If not empty, then there is a distinguished.
1/14/20161 BST Operations Data Structures Ananda Gunawardena.
Trees 3 The Binary Search Tree Section 4.3. Binary Search Tree Also known as Totally Ordered Tree Definition: A binary tree B is called a binary search.
1 Trees - Part II © Dave Bockus. 2 Building a Binary Search Tree h i b c e d f m k a Input: i h b m e c f a d k.
CSCS-200 Data Structure and Algorithms Lecture
CMSC 341 Binary Search Trees. 8/3/2007 UMBC CMSC 341 BST 2 Binary Search Tree A Binary Search Tree is a Binary Tree in which, at every node v, the values.
Definitions Read Weiss, 4.1 – 4.2 Implementation Nodes and Links One Arrays Three Arrays Traversals Preorder, Inorder, Postorder K-ary Trees Converting.
1 Nell Dale Chapter 8 Binary Search Trees Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
1 CMSC 341 Introduction to Trees Textbook sections:
1 Trees. 2 Outline Preliminaries –What is Tree? –Implementation of Trees using C++ –Tree traversals and applications Binary Trees Binary Search Trees.
CC 215 Data Structures Trees
Binary Search Tree (BST)
Source Code for Data Structures and Algorithm Analysis in C (Second Edition) – by Weiss
CSE 373 Data Structures Lecture 7
Chapter 20: Binary Trees.
Map interface Empty() - return true if the map is empty; else return false Size() - return the number of elements in the map Find(key) - if there is an.
CMSC 341 Lecture 10 Binary Search Trees
CMPE 180A Data Structures and Algorithms in C++ April 26 Class Meeting
Trees 3: The Binary Search Tree
Chapter 21: Binary Trees.
Trees, Binary Trees, and Binary Search Trees
Trees.
Lec 12 March 9, 11 Mid-term # 1 (March 21?)
CMSC 341 Binary Search Trees 11/19/2018.
Trees CSE 373 Data Structures.
Lecture No.16 Data Structures Dr. Sohail Aslam.
CMSC 341 Binary Search Trees.
CMSC 341 Binary Search Trees 1/3/2019.
Binary Trees, Binary Search Trees
CMSC 341 Binary Search Trees 2/23/2019.
CMSC 341 Binary Search Trees.
Tree.
CMSC 341 Binary Search Trees 5/8/2019.
Trees BST, AVL, SPLAY TREES
Trees CSE 373 Data Structures.
CMSC 341 Binary Search Trees 5/28/2019.
CMSC 341 Binary Search Trees 8/3/2007 CMSC 341 BST.
Trees CSE 373 Data Structures.
CMSC 341 Binary Search Trees 2/21/2006.
Binary Trees, Binary Search Trees
Presentation transcript:

1 Trees 3: The Binary Search Tree Reading: Sections 4.3 and 4.6

2 Binary Search Tree Also known as Totally Ordered Tree Definition: A binary tree B is called a binary search tree iff: –There is an order relation < defined for the vertices of B –For any vertex v, and any descendant u of v.left, u < v –For any vertex v, and any descendent w of v.right, v < w root

3 Binary Search Tree Which one is NOT a BST?

4 Binary Search Tree Consequences: –The smallest element in a binary search tree (BST) is the “left- most” node –The largest element in a BST is the “right-most” node –Inorder traversal of a BST encounters nodes in increasing order root

5 Binary Search using BST Assumes nodes are organized in a totally ordered binary tree –Begin at root node –Descend using comparison to make left/right decision if (search_value < node_value) go to the left child else if (search_value > node_value) go to the right child else return true (success) –Until descending move is impossible –Return false (failure)

6 Binary Search using BST Runtime <= descending path length <= depth of tree If tree has enough branching, runtime <= O(log size)

BST Class Template Template Class BinarySearchTree { public: BinarySearchTree(); BinarySearchTree(const BinarySearchTree & rhs);// copy BinarySearchTree(BinarySearchTree &&rhs);// move ~BinarySearchTree(); const Comparable & findMin() const; const Comparable & findMax() const; bool contains(const Comparable &x) const; bool isEmpty() const; void printTree(ostream & out = std::cout) const; void makeEmpty(); void insert(const Comparable &x); void insert(Comparable &&x);// move void remove(const Comparable &x); BinarySearchTree & operator=(const BinarySearchTree &rhs); BinarySearchTree & operator=(BinarySearchTree && rhs);// move 7

BST Class Template (Cont’d) private: struct BinaryNode { Comparable element; BinaryNode *left; BinaryNode *right; BinaryNode(const Comparable &theElement, BinaryNode *lt, BinaryNode *rt) : element{theElement}, left{lt}, right{rt} {} BinaryNode(Comparable && theElement, BinaryNode *lt, BinaryNode *rt) : element{std::move(theElement)}, left{lt}, right{rt} {} }; BinaryNode *root; void insert(const Comparable &x, BinaryNode * & t); void insert(Comparable &&x, BinaryNode * &t); void remove(const Comparable &x, BinaryNode * & t); BinaryNode *findMin(BinaryNode *t) const; BinaryNode *findMax(BinaryNode *t) const; bool contains(const Comparable &x, BinaryNode *t) const; void makeEmpty(BinaryNode * &t); void printTree(BinaryNode *t, ostream & out) const; BinaryNode *clone(BinaryNode *t) const; }; 8 Internal functions used in recursive calls Pointer passed by reference (why?)

9 BST: Public members calling private recursive functions

/** * Internal method to test if an item is in a subtree. * x is item to search for. * t is the node that roots the subtree. */ bool contains( const Comparable & x, BinaryNode *t ) const { if( t == nullptr ) return false; else if( x element ) return contains( x, t->left ); else if( t->element < x ) return contains( x, t->right ); else return true; // Match } 10 BST: Searching for an element

/** * Internal method to find the smallest item in a subtree t. * Return node containing the smallest item. */ BinaryNode * findMin( BinaryNode *t ) const { if( t == nullptr ) return nullptr; if( t->left == nullptr ) return t; return findMin( t->left ); } 11 BST: Find the smallest element Tail recursion

/** * Internal method to find the largest item in a subtree t. * Return node containing the largest item. */ BinaryNode * findMax( BinaryNode *t ) const { if( t != nullptr ) while( t->right != nullptr ) t = t->right; return t; } 12 BST: Find the biggest element Non-recursive

13 BST: Insertion (5) Before insertion After insertion

14 BST: Insertion (contd.) Strategy: Traverse the tree as if searching for x with contains() Insert when you reach a null pointer t. /** * Internal method to insert into a subtree. * x is the item to insert. * t is the node that roots the subtree. * Set the new root of the subtree. */ void insert( const Comparable & x, BinaryNode * & t ) { if( t == nullptr ) t = new BinaryNode{ x, nullptr, nullptr }; else if( x element ) insert( x, t->left ); else if( t->element < x ) insert( x, t->right ); else ; // Duplicate; do nothing } How to implement the move version of insert()?

15 BST: Deletion Before deleting (4) After deleting (4) Deleting a node with one child Deletion Strategy: Bypass the node being deleted

16 BST: Deletion (contd.) Before deleting (2) After deleting (2) Deleting a node with two children Deletion Strategy: Replace the node with smallest node in the right subtree

/** * Internal method to remove from a subtree. * x is the item to remove. * t is the node that roots the subtree. */ void remove( const Comparable & x, BinaryNode * & t ) { if( t == nullptr ) return; // Item not found; do nothing if( x element ) remove( x, t->left ); else if( t->element < x ) remove( x, t->right ); else if( t->left != nullptr && t->right != nullptr ) { // two children t->element = findMin( t->right )->element; remove( t->element, t->right ); } else { BinaryNode *oldNode = t; t = ( t->left != nullptr ) ? t->left : t->right; delete oldNode; } 17 BST: Deletion (contd.)

18 BST: Lazy Deletion Another deletion strategy –Don’t delete! –Just mark the node as deleted. –Wastes space –But useful if deletions are rare or space is not a concern.

19 BST: Destructor /** * Destructor for the tree */ ~BinarySearchTree( ) { makeEmpty( ); } /** * Internal method to make subtree empty. */ void makeEmpty( BinaryNode * & t ) { if( t != nullptr ) { makeEmpty( t->left ); makeEmpty( t->right ); delete t; } t = nullptr; }

/** * Copy constructor */ BinarySearchTree( const BinarySearchTree & rhs ) : root{ nullptr } { root = clone( rhs.root ); } /** * Internal method to clone subtree. */ BinaryNode * clone( BinaryNode *t ) const { if( t == nullptr ) return nullptr; else return new BinaryNode{ t->element, clone( t->left ), clone( t->right ) }; } 20 BST: Assignment Operator

Tree Traversal (Inorder) // Print the tree contents in sorted order. void printTree( ostrem & out ) const { if( isEmpty( ) ) cout << "Empty tree" << endl; else printTree( root, out); } /** * Internal method to print a subtree rooted at t in sorted order. */ void printTree( BinaryNode *t, ostream & out ) const { if( t != nullptr ) { printTree( t->left ); out element << endl; printTree( t->right ); } 21

22 BST: Insertion Bias Start with an empty tree. Insert elements in sorted order What tree do you get? How do you fix it?

23 BST: Deletion Bias After large number of alternating insertions and deletions Why this bias? How do you fix it?

Template > class BinarySearchTree { public: // same methods, with Object replacing Comparable private: BinaryNode *root; Comparable isLessThan; // same methods, with Object replacing Comparable bool contains( const Comparable & x, BinaryNode *t ) const { if( t == nullptr ) return false; else if( isLessThan(x, t->element )) return contains( x, t->left ); else if( isLessThan(t->element,x )) return contains( x, t->right ); else return true; // Match } }; 24 BST: Search using function objects

25 Reading assignment Sections 4.4, 4.7, and 4.8