COSC2007 Data Structures II

Slides:



Advertisements
Similar presentations
Course: Programming II - Abstract Data Types ADT Binary Search TreeSlide Number 1 The ADT Binary Search Tree Definition The ADT Binary Search Tree is a.
Advertisements

CSC 205 – Java Programming II Lecture 35 April 17, 2002.
BST Search To find a value in a BST search from the root node: If the target is less than the value in the node search its left subtree If the target is.
1 Jake’s Pizza Shop Owner Jake Manager Chef Brad Carol Waitress Waiter Cook Helper Joyce Chris Max Len.
© 2006 Pearson Addison-Wesley. All rights reserved11 B-1 Chapter 11 (continued) Trees.
Binary Search Trees Briana B. Morrison Adapted from Alan Eugenio.
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.
Marc Smith and Jim Ten Eyck
© 2006 Pearson Addison-Wesley. All rights reserved13 A-1 Chapter 13 Advanced Implementation of Tables.
Deletion algorithm – Phase 2: Remove node or replace its with successor TreeNode deleteNode(TreeNode n) { // Returns a reference to a node which replaced.
Binary Search Trees Chapter 7 Objectives
By : Budi Arifitama Pertemuan ke Objectives Upon completion you will be able to: Create and implement binary search trees Understand the operation.
Properties: -Each node has a value -The left subtree contains only values less than the parent node’s value -The right subtree contains only values greater.
Trees Chapter 8. 2 Tree Terminology A tree consists of a collection of elements or nodes, organized hierarchically. The node at the top of a tree is called.
Review Binary Tree Binary Tree Representation Array Representation Link List Representation Operations on Binary Trees Traversing Binary Trees Pre-Order.
CS Data Structures Chapter 15 Trees Mehmet H Gunes
Binary Trees Chapter Definition And Application Of Binary Trees Binary tree: a nonlinear linked list in which each node may point to 0, 1, or two.
© 2011 Pearson Addison-Wesley. All rights reserved 11 B-1 Chapter 11 (continued) Trees.
CISC220 Fall 2009 James Atlas Lecture 13: Trees. Skip Lists.
Tree (new ADT) Terminology:  A tree is a collection of elements (nodes)  Each node may have 0 or more successors (called children)  How many does a.
Data Structures Balanced Trees 1CSCI Outline  Balanced Search Trees 2-3 Trees Trees Red-Black Trees 2CSCI 3110.
COSC2007 Data Structures II Chapter 11 Trees V. 2 Topics TreeSort Save/Restore into/from file General Trees.
Binary Search Trees Binary Search Trees (BST)  the tree from the previous slide is a special kind of binary tree called a binary.
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.
Tree Implementations Chapter 16 Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013.
Chapter 11 B Trees. © 2004 Pearson Addison-Wesley. All rights reserved 11 B-2 The ADT Binary Search Tree A deficiency of the ADT binary tree which is.
COSC2007 Data Structures II Chapter 11 Trees IV. 2 Topics ADT BST Implementations Efficiency TreeSort Save/Restore into/from file General Trees.
COSC2007 Data Structures II Chapter 12 Tables & Priority Queues III.
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Modified for use at Midwestern State University Chapter.
1 Chapter 7 Objectives Upon completion you will be able to: Create and implement binary search trees Understand the operation of the binary search tree.
CSC 205 Java Programming II Lecture 28 BST Implementation.
ADT Binary Search Tree Ellen Walker CPSC 201 Data Structures Hiram College.
Trees Chapter 10. CS 308 2Chapter Trees Preview: Preview: The data organizations presented in previous chapters are linear, in that items are one.
COSC 2007 Data Structures II Chapter 13 Advanced Implementation of Tables I.
Copyright © 2012 Pearson Education, Inc. Chapter 20: Binary Trees.
Data Structures: A Pseudocode Approach with C, Second Edition 1 Chapter 7 Objectives Create and implement binary search trees Understand the operation.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 20: Binary Trees.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 20: Binary Trees.
Binary Search Trees Chapter 7 Objectives
Heap Chapter 9 Objectives Define and implement heap structures
Trees Chapter 15.
Data Structures Balanced Trees CSCI 2720 Spring 2007.
AA Trees.
CSCE 3110 Data Structures & Algorithm Analysis
Trees Chapter 11 (continued)
Trees Chapter 11 (continued)
The Tree Data Structure
BST Trees
Binary search tree. Removing a node
CISC220 Fall 2009 James Atlas Lecture 13: Binary Trees.
Binary Search Tree (BST)
CS 302 Data Structures Trees.
Chapter 10 Search Trees 10.1 Binary Search Trees Search Trees
Binary Search Trees.
Lecture 22 Binary Search Trees Chapter 10 of textbook
Chapter 16 Tree Implementations
Binary Search Trees Why this is a useful data structure. Terminology
Chapter 20: Binary Trees.
Ch. 11 Trees 사실을 많이 아는 것 보다는 이론적 틀이 중요하고, 기억력보다는 생각하는 법이 더 중요하다.
Data Structures Balanced Trees CSCI
Chapter 21: Binary Trees.
Lec 12 March 9, 11 Mid-term # 1 (March 21?)
CS202 - Fundamental Structures of Computer Science II
Search Sorted Array: Binary Search Linked List: Linear Search
Chapter 16 Tree Implementations
Trees Chapter 10.
B.Ramamurthy Chapter 9 CSE116A,B
CSC 205 – Java Programming II
CSC 205 – Java Programming II
Chapter 11 Trees © 2011 Pearson Addison-Wesley. All rights reserved.
Presentation transcript:

COSC2007 Data Structures II September 7, 2019 COSC2007 Data Structures II Chapter 11 Trees III Trees

Topics ADT Binary-Search Tree (BST) Operations Insertion Deletion Retrieval traversal

ADT BST Problem of general BT BST 40 70 60 30 20 10 50 Problem of general BT Searching for a particular item is difficult Solution Use BST BST Each node satisfies the following properties: n’s value > all values in its left subtree TL n’s value < all values in its right subtree TR Both TL and TR are BST Insertion, deletion, and retrieval operations ? 60 70 20 10 40 50 30

ADT BST Operations

ADT BST Implementation Implementation of the Structure The record, or item, in TreeNode class of the tree should extend the following class public abstract class KeyedItem { private Comparable searchKey; public KeyedItem (Comparable key) { serachKey =key; } // constructor public Comparable getKey () // returns search key { return searchKey; } // end getKey }

Using ADT BST Example BST of names Each node will be a record representing a Person New Class: Person Class (Key = ID) public class Person extends KeyedItem { private FullName name; // Key item is the id private string phoneNumber; private Address address; public Person(FullName name, String id, String phone, Address addr) { super (id); //key is the ID this.name = name; phoneNumber = phone; address = addr; } public String toString () ( return getKey()+ “ #” + name; // other methods } // end class

ADT BST Implementation Implementation of BST Operations A search algorithm is needed as the basis of some operations: insertion deletion retrieval 57 18 5 40 -8 14 28 56 184 63 229 387 root

Searching for a node with a value 57 18 5 40 -8 14 28 56 184 63 229 387 root Suppose I gave you a key, like 28. How would you do it?

Searching for a node with a value 57 18 5 40 -8 14 28 56 184 63 229 387 root Search key = 28 Compare against root If <, choose left If ==, return root If >, choose right Recurse on left or right subtree until either find element run off a leaf node (failure) compare and choose

Searching for a node with a value Pseudocode of Search Strategy : search (bst, searchKey) // Searches the BST bst for the item whose key is searchKey if (bst is empty) The desired record is not found else if (searchKey = = search key of root’s item) The desired record is found else if (searchKey < searck key of root’s item) search (Left subtree of bst, serachKey) else search (Right subtree of bst, serachKey) 60 70 20 10 40 50 30

Searching for a node with a value The shape of the tree doesn’t affect the search algorithm. However, the algorithm works more efficiently on some trees than the others Tom Jane Bob Alan Wendy Nancy Ellen Unbalanced BST Skewed BST Balanced BST Full & Complete BST

BST Insertion Insertion should preserve the tree's properties First search for the correct position to insert the given item If the item doesn’t exist in the BST , item will be inserted as a new leaf Search will always terminate at an empty subtree

BST Insertion Suppose I want to insert the key 60 to this tree. 57 18 40 -8 14 28 56 184 63 229 387 root Suppose I want to insert the key 60 to this tree.

BST Insertion Search for the key, as we did earlier. If we don’t find it, the place where we ‘fall off the tree’ is where a new node containing the key should be inserted. If we do find it, we have to have a convention about where to put a duplicate item (arbitrarily choose the left subtree). BST Insertion 57 18 5 40 -8 14 28 56 184 63 229 387 root compare and choose Element should be here if it’s in the tree! In this case, we need to create a new node as the left subtree of the node containing 63

BST Insertion 60 70 20 10 40 50 30 BST Insertion Pseudocode: // insert newItem into the BST of which treeNode is the root insertItem (treeNode, NewItem) { if (treeNode is null) Create a new node and let treeNode point to it Create a new node with newItem as its data portion Set the reference in the new node to null } else if (newItem.getKey( ) < treeNode.getItem().getKey ( ) ) treeNode.setLeft(insertItem(treeNode.getLeft(), newItem)) else treeNode.setRight(insertItem(treeNode.getRight(),newItem))

BST Deletion Suppose I wanted to remove a key (and associated data item) from a tree. How would I do it? More involved than insertion Several cases to consider: N is a leaf N has only one left child N has only one right child N has two children 57 18 5 40 -8 14 28 56 184 63 229 387 root

BST Deletion To remove a key R from the binary search tree first requires that we find R. (we know how to do this) If R is (in) a leaf node, then R’s parent has its corresponding child set to null. If R is in a node that has one child, then R’s parent has its corresponding pointer set to R’s child. If R is in a node that has two children, the solution is more difficult. The deletion strategy should preserve the BST property

BST Deletion To remove a key R from the binary search tree first requires that we find R. (we know how to do this) If R is (in) a leaf node, then R’s parent has its corresponding child set to null. If R is in a node that has one child, then R’s parent has its corresponding pointer set to R’s child. If R is in a node that has two children, the solution is more difficult. The deletion strategy should preserve the BST property

Delete a leaf node Case 1: N is a Leaf Set the pointer in the leaf’s parent to NULL  

Delete a node with one child Case 2: N has only one child Let N’s parent adopt N’s child

Delete a node with two children Don’t remove the NODE containing the key 18. Instead, consider replacing its key using a key from the left or right subtree. Then remove THAT node from the tree. So what values could we use. What about 14 or 28? Max value from left subtree or minimum value from right subtree! Why are these the one’s to use? 57 18 5 40 -8 14 28 56 184 63 229 387 root

Delete a node with two children 57 14 5 40 -8 28 56 184 63 229 387 root 57 28 5 40 -8 14 56 184 63 229 387 root Notice that in both cases, the binary tree property is preserved.

BST Deletion deleteItem (rootNode, searchKey) { //delete from BST with root rootNode the item whose key equals searchKey. Return the root node of the resulting tree if (treeNode == null) throw TreeExceoption // item not found else if ( searchKey equals the key in rootNode item) // item at root, delete the rootNode, a new root of the tree is returned newNode =deleteNode(rootNode, serachKey) return newNode; else if (searchKey is less than the key in rootNode item) newLeft =deleteItem(rootNode.getleft(), searchKey) rootNode.setLeft(newLeft); return rootNode; //return rootNode with new left subtree else newRight=deleteItem(rootNode.getRight(), searchKey) rootNode.setRight(newRight); return rootNode; //return rootNode with new right subtre }

BST Deletion // Deletes item in node to which treeNode references .  deleteNode (treeNode) { // Deletes item in node to which treeNode references . //return the root node of the resulting tree if (treeNode is a leaf) nodePtr=null; //remove leaf from the tree else if (treeNode has only one child C) //c replaces treeNode as the child of treeNode’s parent { if (C is the left child of treeNode) return treeNode.getLeft(); else return treeNode.getRight(); } 60 70 20 10 40 50 30

BST Deletion else // treeNode has 2 children // find the inorder successor of the search key in tree node: it is the leftmost node of the right subtree { replacementItem = findLeftMost (treeNode.getRight()); replacementRChild = deleteLeftMost(treeNode.getRight()) set treeNode’s item to replacement set treeNode’s right child to replacemenrRChild return treeNode }

BST Deletion findLeftMost (treeNode) 60 70 20 10 40 50 30 BST Deletion  findLeftMost (treeNode) // return the item that is the leftmost descendent of the tree rooted at treeNode if (treeNode.getLeft() == null) //this is the node you want, so return it items return treeNode.getItem() else return findLeftMost(treeNode.getLeft())

BST Deletion deleteLeftMost (treeNode) 60 70 20 10 40 50 30 BST Deletion  deleteLeftMost (treeNode) // delete the node that is the leftmost descendent // of the tree rooted at treeNode, return subtree of deleted node if (treeNode.getLeft() == null) //this is the node you want, it has no left child, but might has a right subtree, the return value of this method is a child reference of treeNode’s parent; thus following “movs up” treeNode’s right subtree return treeNode.getRight() else replacementLChild = deleteLeftMost(treeNode.getLeft()) treeNode.setLeft (replacementLChild) return treeNode

BST Retrieval Retrieve: Returns the item with the desired search key By refining the search algorithm, we can implement the retrieval operation

BST Retrieval search (bst, searchKey) //search theBST for the item whose search key is searchKey if (bst is empty) item not found else if (searchKey == search key of bst’s root item ) the desired record is found else if (searchKey < search key of bst’s root item ) search(left subtree of bst, searchKey) else search(right subtree of bst, searchKey) 60 70 20 10 40 50 30

BST Retrieval retrieveItem (treeNode, searchKey) 60 70 20 10 40 50 30 //return item whose search key equals searchKey //if no such item, return null if (treeNode == null) treeItem = null // tree is empty else if (searchKey == treeNode.getItem().getkey() ) //item is at root of some subtree treeItem = treeNode.getItem() else if (searchKey < treeNode.getItem().getkey() ) //search left subtree retrieveItem (treeNode.getleft(), searchKey) else retrieveItem (treeNode.getRight(), searchKey) return treeItem

BST Traversal The implementation should include the following methods: Public Member Methods void preorderTraverse (bst); void inorderTraverse (bst); void postorderTraverse (bst);