Trees 3: The Binary Search Tree

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)
Binary Trees, Binary Search Trees CMPS 2133 Spring 2008.
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.
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
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,
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.
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.
1 Data Structures CSCI 132, Spring 2014 Lecture 36 Binary Search Trees.
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.
Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.
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.
CSCS-200 Data Structure and Algorithms Lecture
1 CSC 427: Data Structures and Algorithm Analysis Fall 2004 Trees and nonlinear structures  tree structure, root, leaves  recursive tree algorithms:
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.
1 Nell Dale Chapter 8 Binary Search Trees Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
1 Trees 3: The Binary Search Tree Reading: Sections 4.3 and 4.6.
CISC220 Fall 2009 James Atlas Lecture 13: Binary Trees.
Binary Search Tree (BST)
Source Code for Data Structures and Algorithm Analysis in C (Second Edition) – by Weiss
Trees.
Binary Search Trees Why this is a useful data structure. Terminology
Binary Trees, Binary Search Trees
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
Chapter 21: Binary Trees.
Trees, Binary Trees, and Binary Search Trees
Linked Lists.
Trees.
Lec 12 March 9, 11 Mid-term # 1 (March 21?)
CMSC 341 Binary Search Trees 11/19/2018.
CMSC 341 Introduction to Trees.
CMSC 341 Introduction to Trees.
Lecture No.16 Data Structures Dr. Sohail Aslam.
CMSC 341 Binary Search Trees.
Trees Basic concepts of trees Implementation of trees
CMSC 341 Binary Search Trees 1/3/2019.
Binary Search Trees.
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
CMSC 341 Binary Search Trees 5/28/2019.
CMSC 341 Binary Search Trees 8/3/2007 CMSC 341 BST.
CMSC 341 Binary Search Trees 2/21/2006.
Binary Trees, Binary Search Trees
Data Structures Using C++ 2E
Presentation transcript:

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

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 4 2 6 1 3 5 7

Binary Search Tree Which one is NOT a BST?

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 4 2 6 1 3 5 7

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)

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

BST Class Template Template <typename Comparable> 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

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; Pointer passed by reference (why?) Internal functions used in recursive calls

BST: Public members calling private recursive functions

BST: Searching for an element /** * 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 < t->element ) return contains( x, t->left ); else if( t->element < x ) return contains( x, t->right ); else return true; // Match }

BST: Find the smallest 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 ); } Tail recursion

BST: Find the biggest element /** * 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; } Non-recursive

BST: Insertion (5) Before insertion After insertion

BST: Insertion (contd.) /** * 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 < t->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()? Strategy: Traverse the tree as in searching for t with contains() Insert if you cannot find the element t.

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

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

BST: Deletion (contd.) /** * 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 < t->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;

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.

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

BST: Copy Constructor /** * 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 ) };

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 << t->element << endl; printTree( t->right );

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

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

Reading assignment Sections 4.4, 4.7, and 4.8