1 Nell Dale Chapter 8 Binary Search Trees Modified from the slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data.

Slides:



Advertisements
Similar presentations
Chapter 8 Binary Search Tree 1 Fall Binary Trees 2 A structure with: i) a unique starting node (the root), in which ii) each node has up to two.
Advertisements

1 Nell Dale Chapter 9 Trees Plus Modified from the slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
1 A Two-Level Binary Expression ‘-’ ‘8’ ‘5’ treePtr INORDER TRAVERSAL : has value 3 PREORDER TRAVERSAL: POSTORDER TRAVERSAL: 8 5 -
Binary Search Trees CS 308 – Data Structures What is a binary tree? Property1: each node can have up to two successor nodes (children) –The predecessor.
1 Jake’s Pizza Shop Owner Jake Manager Chef Brad Carol Waitress Waiter Cook Helper Joyce Chris Max Len.
EC-211 DATA STRUCTURES LECTURE Tree Data Structure Introduction –The Data Organizations Presented Earlier are Linear in That Items are One After.
InOrder Traversal Algorithm // InOrder traversal algorithm inOrder(TreeNode n) { if (n != null) { inOrder(n.getLeft()); visit(n) inOrder(n.getRight());
Trees, Binary Trees, and Binary Search Trees COMP171.
1 Chapter 8 Binary Search Trees. 2 Owner Jake Manager Chef Brad Carol Waitress Waiter Cook Helper Joyce Chris Max Len Jake’s Pizza Shop.
1 Nell Dale Chapter 9 Trees Plus Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
Data Structures Data Structures Topic #8. Today’s Agenda Continue Discussing Table Abstractions But, this time, let’s talk about them in terms of new.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 19 Binary.
1 CS308 Data Structures An application of binary trees: Binary Expression Trees.
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 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County.
1 Nell Dale Chapter 6 Lists Plus Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
CSCE 3110 Data Structures & Algorithm Analysis Binary Search Trees Reading: Chap. 4 (4.3) Weiss.
1 Nell Dale Chapter 9 Trees Plus Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
Chapter 8 Binary Search Trees. Owner Jake Manager Chef Brad Carol Waitress Waiter Cook Helper Joyce Chris Max Len Jake’s Pizza Shop.
Data Structures - CSCI 102 Binary Tree In binary trees, each Node can point to two other Nodes and looks something like this: template class BTNode { public:
Binary Search Trees. What is a binary tree? Property 1: each node can have up to two successor nodes.
1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus.
Recursion Bryce Boe 2013/11/18 CS24, Fall Outline Wednesday Recap Lab 7 Iterative Solution Recursion Binary Tree Traversals Lab 7 Recursive Solution.
CS Data Structures Chapter 15 Trees Mehmet H Gunes
Trees.ppt1 Introduction Many data structures are linear –unique first component –unique last component –other components have unique predecessor and successor.
1 Lecture 11 POLYNOMIALS and Tree sort 2 INTRODUCTION EVALUATING POLYNOMIAL FUNCTIONS Horner’s method Permutation Tree sort.
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.
1 Trees A tree is a data structure used to represent different kinds of data and help solve a number of algorithmic problems Game trees (i.e., chess ),
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.
Topic 15 The Binary Search Tree ADT Binary Search Tree A binary search tree (BST) is a binary tree with an ordering property of its elements, such.
 Trees Data Structures Trees Data Structures  Trees Trees  Binary Search Trees Binary Search Trees  Binary Tree Implementation Binary Tree Implementation.
Lec 15 Oct 18 Binary Search Trees (Chapter 5 of text)
Chapter 8 Binary Search Trees. 2 Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor.
Chapter 8 Binary Search Trees 1. Owner Jake Manager Chef Brad Carol Waitress Waiter Cook Helper Joyce Chris Max Len Jake’s Pizza Shop 2.
1 Chapter 16 Linked Structures Dale/Weems. 2 Chapter 16 Topics l Meaning of a Linked List l Meaning of a Dynamic Linked List l Traversal, Insertion and.
Search: Binary Search Trees Dr. Yingwu Zhu. Linear Search Collection of data items to be searched is organized in a list x 1, x 2, … x n Assume == and.
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.
Computer Science and Software Engineering University of Wisconsin - Platteville 10. Binary Search Tree Yan Shi CS/SE 2630 Lecture Notes Partially adopted.
1 Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus Trees.
1/14/20161 BST Operations Data Structures Ananda Gunawardena.
1 Binary Trees and Binary Search Trees Based on Dale & Co: Object-Oriented Data Structures using C++ (graphics)
1 Lecture 21: Binary Search Tree delete etc. operations Lecturer: Santokh Singh CompSci 105 SS 2005 Principles of Computer Science.
Binary Search Tree. Tree  A nonlinear data structure consisting of nodes, each of which contains data and pointers to other nodes.  Each node has only.
Binary Search Trees (BST)
Binary Search Trees … From
1 C++ Plus Data Structures Nell Dale Chapter 5 Linked Structures Modified from the slides by Sylvia Sorkin, Community College of Baltimore County - Essex.
Chapter 8 Binary Search Trees. Chapter 8: Binary Search Trees 8.1 – Trees 8.2 – The Logical Level 8.3 – The Application Level 8.4 – The Implementation.
Copyright © 2012 Pearson Education, Inc. Chapter 20: Binary Trees.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 20: Binary Trees.
Search: Binary Search Trees Dr. Yingwu Zhu. Review: Linear Search Collection of data items to be searched is organized in a list x 1, x 2, … x n – Assume.
1 Nell Dale Chapter 8 Binary Search Trees Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures.
Binary Search Trees CS Goals Define and use the following terminology: binary tree root descendant subtree binary search tree parent level ancestor.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 20: Binary Trees.
1 Trees 3: The Binary Search Tree Reading: Sections 4.3 and 4.6.
Binary Trees and Binary Search Trees
Chapter 8 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.
Chapter 21: Binary Trees.
C++ Plus Data Structures
Find in a linked list? first last 7  4  3  8 NULL
Chapter 8 Binary Search Tree
Yan Shi CS/SE 2630 Lecture Notes
C++ Plus Data Structures
Tree (new ADT) Terminology: A tree is a collection of elements (nodes)
Presentation transcript:

1 Nell Dale Chapter 8 Binary Search Trees Modified from the slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus C++ Plus Data Structures

2 for an element in a sorted list stored sequentially l in an array: O(Log 2 N) l in a linked list: ? (midpoint = ?) Binary search

3 l Introduce some basic tree vocabulary l Develop algorithms l Implement operations needed to use a binary search tree Goals of this chapter

4 Jake’s Pizza Shop Owner Jake Manager Chef Brad Carol Waitress Waiter Cook Helper Joyce Chris Max Len

5 Owner Jake Manager Chef Brad Carol Waitress Waiter Cook Helper Joyce Chris Max Len A Tree Has a Root Node ROOT NODE

6 Owner Jake Manager Chef Brad Carol Waitress Waiter Cook Helper Joyce Chris Max Len Leaf nodes have no children LEAF NODES

7 Owner Jake Manager Chef Brad Carol Waitress Waiter Cook Helper Joyce Chris Max Len A Tree Has Levels LEVEL 0 Level of a node: its distance from the root

8 Owner Jake Manager Chef Brad Carol Waitress Waiter Cook Helper Joyce Chris Max Len Level One LEVEL 1

9 Owner Jake Manager Chef Brad Carol Waitress Waiter Cook Helper Joyce Chris Max Len Level Two LEVEL 2

10 l Maximum number of levels: N l Minimum number of levels: logN + 1 e.g., N=8, 16, …, 1000 A binary tree with N nodes:

11 the maximum level in a tree The height of a tree: -- a critical factor in determining how efficiently we can search for elements

12 Owner Jake Manager Chef Brad Carol Waitress Waiter Cook Helper Joyce Chris Max Len A Subtree LEFT SUBTREE OF ROOT NODE

13 Owner Jake Manager Chef Brad Carol Waitress Waiter Cook Helper Joyce Chris Max Len Another Subtree RIGHT SUBTREE OF ROOT NODE

14 A binary tree is a structure in which: Each node can have at most two children, and in which a unique path exists from the root to every other node. The two children of a node are called the left child and the right child, if they exist. Binary Tree

15 A Binary Tree Q V T K S A E L

16 A Binary Tree ? Q V T K S A E L

17 How many leaf nodes? Q V T K S A E L

18 How many descendants of Q? Q V T K S A E L

19 How many ancestors of K? Q V T K S A E L

20 Implementing a Binary Tree with Pointers and Dynamic Data Q V T K S A E L

21 Each node contains two pointers template struct TreeNode { ItemType info; // Data member TreeNode * left; // Pointer to left child TreeNode * right; // Pointer to right child };. left. info. right NULL ‘A’ 6000

// BINARY SEARCH TREE SPECIFICATION template class TreeType { public: TreeType ( ); // constructor ~TreeType ( ); // destructor bool IsEmpty ( ) const; bool IsFull ( ) const; int NumberOfNodes ( ) const; void InsertItem ( ItemType item ); void DeleteItem (ItemType item ); void RetrieveItem ( ItemType& item, bool& found ); void PrintTree (ofstream& outFile) const;... private: TreeNode * root; }; 22

23 TreeType CharBST; ‘J’ ‘E’ ‘A’ ‘S’ ‘H’ TreeType ~TreeType IsEmpty InsertItem Private data: root RetrieveItem PrintTree.

24 A Binary Tree Q V T K S A E L Search for ‘S’?

25 A special kind of binary tree in which: 1. Each node contains a distinct data value, 2. The key values in the tree can be compared using “greater than” and “less than”, and 3. The key value of each node in the tree is less than every key value in its right subtree, and greater than every key value in its left subtree. A Binary Search Tree (BST) is...

26 Depends on its key values and their order of insertion. Insert the elements ‘J’ ‘E’ ‘F’ ‘T’ ‘A’ in that order. The first value to be inserted is put into the root node. Shape of a binary search tree... ‘J’

27 Thereafter, each value to be inserted begins by comparing itself to the value in the root node, moving left it is less, or moving right if it is greater. This continues at each level until it can be inserted as a new leaf. Inserting ‘E’ into the BST ‘J’ ‘E’

28 Begin by comparing ‘F’ to the value in the root node, moving left it is less, or moving right if it is greater. This continues until it can be inserted as a leaf. Inserting ‘F’ into the BST ‘J’ ‘E’ ‘F’

29 Begin by comparing ‘T’ to the value in the root node, moving left it is less, or moving right if it is greater. This continues until it can be inserted as a leaf. Inserting ‘T’ into the BST ‘J’ ‘E’ ‘F’ ‘T’

30 Begin by comparing ‘A’ to the value in the root node, moving left it is less, or moving right if it is greater. This continues until it can be inserted as a leaf. Inserting ‘A’ into the BST ‘J’ ‘E’ ‘F’ ‘T’ ‘A’

31 is obtained by inserting the elements ‘A’ ‘E’ ‘F’ ‘J’ ‘T’ in that order? What binary search tree... ‘A’

32 obtained by inserting the elements ‘A’ ‘E’ ‘F’ ‘J’ ‘T’ in that order. Binary search tree... ‘A’ ‘E’ ‘F’ ‘J’ ‘T’ A “degenerate” tree!

33 Another binary search tree Add nodes containing these values in this order: ‘D’ ‘B’ ‘L’ ‘Q’ ‘S’ ‘V’ ‘Z’ ‘J’ ‘E’ ‘A’ ‘H’ ‘T’ ‘M’ ‘K’ ‘P’

34 Is ‘F’ in the binary search tree? ‘J’ ‘E’ ‘A’ ‘H’ ‘T’ ‘M’ ‘K’ ‘V’ ‘P’ ‘Z’‘D’‘Q’‘L’‘B’‘S’

// BINARY SEARCH TREE SPECIFICATION template class TreeType { public: TreeType ( ) ; // constructor ~TreeType ( ) ; // destructor bool IsEmpty ( ) const ; bool IsFull ( ) const ; int NumberOfNodes ( ) const ; void InsertItem ( ItemType item ) ; void DeleteItem (ItemType item ) ; void RetrieveItem ( ItemType& item, bool& found ) ; void PrintTree (ofstream& outFile) const ;... private: TreeNode * root ; }; 35

// SPECIFICATION (continued) // // RECURSIVE PARTNERS OF MEMBER FUNCTIONS template void PrintHelper ( TreeNode * ptr, ofstream& outFile ) ; template void InsertHelper ( TreeNode * & ptr, ItemType item ) ; template void RetrieveHelper ( TreeNode * ptr, ItemType& item, bool& found ) ; template void DestroyHelper ( TreeNode * ptr ) ; 36

// BINARY SEARCH TREE IMPLEMENTATION // OF MEMBER FUNCTIONS AND THEIR HELPER FUNCTIONS // template TreeType :: TreeType ( ) // constructor { root = NULL ; } // template bool TreeType :: IsEmpty( ) const { return ( root == NULL ) ; } 37

template void TreeType :: RetrieveItem ( ItemType& item, bool& found ) { RetrieveHelper ( root, item, found ) ; } template void RetrieveHelper ( TreeNode * ptr, ItemType& item, bool& found) { if ( ptr == NULL ) found = false ; else if ( item info )// GO LEFT RetrieveHelper( ptr->left, item, found ) ; else if ( item > ptr->info ) // GO RIGHT RetrieveHelper( ptr->right, item, found ) ; else { // item = ptr->info ; found = true ; } 38

template void TreeType :: RetrieveItem ( ItemType& item, KF key, bool& found ) // Searches for an element with the same key as item’s key. // If found, store it into item { RetrieveHelper ( root, item, key, found ) ; } template void RetrieveHelper ( TreeNode * ptr, ItemType& item, KF key, bool& found) { if ( ptr == NULL ) found = false ; else if ( key info.key() )// GO LEFT RetrieveHelper( ptr->left, item, key, found ) ; else if ( key > ptr->info.key() ) // GO RIGHT RetrieveHelper( ptr->right, item, key, found ) ; else { item = ptr->info ; found = true ; } 39

template void TreeType :: InsertItem ( ItemType item ) { InsertHelper ( root, item ) ; } template void InsertHelper ( TreeNode * & ptr, ItemType item ) { if ( ptr == NULL ) { // INSERT item HERE AS LEAF ptr = new TreeNode ; ptr->right = NULL ; ptr->left = NULL ; ptr->info = item ; } else if ( item info )// GO LEFT InsertHelper( ptr->left, item ) ; else if ( item > ptr->info ) // GO RIGHT InsertHelper( ptr->right, item ) ; } 40

41 l Find the node in the tree l Delete the node from the tree l Three cases: 1. Deleting a leaf 2. Deleting a node with only one child 3. Deleting a node with two children Note: the tree must remain a binary tree and the search property must remain intact Delete()

template void TreeType :: DeleteItem ( ItemType& item ) { DeleteHelper ( root, item ) ; } template void DeleteHelper ( TreeNode * ptr, ItemType& item) { if ( item info )// GO LEFT DeleteHelper( ptr->left, item ) ; else if ( item > ptr->info ) // GO RIGHT DeleteHelper( ptr->right, item ) ; else { DeleteNode(ptr); // Node is found: call DeleteNode } 42

template void DeleteNode ( TreeNode *& tree ) { ItemType data; TreeNode * tempPtr; tempPtr = tree; if ( tree->left == NULL ) { tree = tree->right; delete tempPtr; } else if (tree->right == NULL ) { tree = tree->left; delete tempPtr; } else { // have two children GetPredecessor(tree->left, item); tree->info = item; DeleteHelper(tree->left, item); // Delete predecessor node (rec) } 43

template void GetPredecessor( TreeNode * tree, ItemType& data ) // Sets data to the info member of the rightmost node in tree { while (tree->right != NULL) tree = tree->right; data = tree->info; } 44

45 Traverse a list: -- forward -- backward Traverse a tree: -- there are many ways! PrintTree()

46 Inorder Traversal: A E H J M T Y ‘J’ ‘E’ ‘A’ ‘H’ ‘T’ ‘M’‘Y’ tree Print left subtree firstPrint right subtree last Print second

// INORDER TRAVERSAL template void TreeType :: PrintTree ( ofstream& outFile ) const { PrintHelper ( root, outFile ) ; } template void PrintHelper ( TreeNode * ptr, ofstream& outFile ) { if ( ptr != NULL ) { PrintHelper( ptr->left, outFile ) ;// Print left subtree outFile info ; PrintHelper( ptr->right, outFile ) ;// Print right subtree } 47

48 Preorder Traversal: J E A H T M Y ‘J’ ‘E’ ‘A’ ‘H’ ‘T’ ‘M’‘Y’ tree Print left subtree secondPrint right subtree last Print first

49 ‘J’ ‘E’ ‘A’ ‘H’ ‘T’ ‘M’‘Y’ tree Print left subtree firstPrint right subtree second Print last Postorder Traversal: A H E M Y T J

template TreeType :: ~TreeType ( )// DESTRUCTOR { DestroyHelper ( root ) ; } template void DestroyHelper ( TreeNode * ptr ) // Post: All nodes of the tree pointed to by ptr are deallocated. { if ( ptr != NULL ) { DestroyHelper ( ptr->left ) ; DestroyHelper ( ptr->right ) ; delete ptr ; } 50

51 Read Text … Iterative Insertion and Deletion

52 l Is the depth of recursion relatively shallow? Yes. l Is the recursive solution shorter or clearer than the nonrecursive version? Yes. l Is the recursive version much less efficient than the nonrecursive version? No. Recursion or Iteration? Assume: the tree is well balanced.

53 Use a recursive solution when (Chpt. 7): The depth of recursive calls is relatively “shallow” compared to the size of the problem. l The recursive version does about the same amount of work as the nonrecursive version. l The recursive version is shorter and simpler than the nonrecursive solution. SHALLOW DEPTH EFFICIENCY CLARITY

54 BST: l Quick random-access with the flexibility of a linked structure l Can be implemented elegantly and concisely using recursion l Takes up more memory space than a singly linked list l Algorithms are more complicated Binary Search Trees (BSTs) vs. Linear Lists

55 End