10 Binary-Search-Tree Data Structure  Binary-trees and binary-search-trees  Searching  Insertion  Deletion  Traversal  Implementation of sets using.

Slides:



Advertisements
Similar presentations
Chapter 7. Binary Search Trees
Advertisements

4 Linked-List Data Structures  Linked-lists: singly-linked-lists, doubly-linked-lists  Insertion  Deletion  Searching © 2008 David A Watt, University.
Binary Trees, Binary Search Trees CMPS 2133 Spring 2008.
Binary Trees, Binary Search Trees COMP171 Fall 2006.
Fall 2007CS 2251 Trees Chapter 8. Fall 2007CS 2252 Chapter Objectives To learn how to use a tree to represent a hierarchical organization of information.
1 Trees. 2 Outline –Tree Structures –Tree Node Level and Path Length –Binary Tree Definition –Binary Tree Nodes –Binary Search Trees.
CS 206 Introduction to Computer Science II 09 / 22 / 2008 Instructor: Michael Eckmann.
BST Data Structure A BST node contains: A BST contains
Lec 15 April 9 Topics: l binary Trees l expression trees Binary Search Trees (Chapter 5 of text)
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L12 (Chapter 20) Lists, Stacks,
CS 206 Introduction to Computer Science II 02 / 11 / 2009 Instructor: Michael Eckmann.
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
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.
Chapter 08 Binary Trees and Binary Search Trees © John Urrutia 2013, All Rights Reserved.
C o n f i d e n t i a l HOME NEXT Subject Name: Data Structure Using C Unit Title: Trees.
More Trees COL 106 Amit Kumar and Shweta Agrawal Most slides courtesy : Douglas Wilhelm Harder, MMath, UWaterloo
Binary Trees Chapter 6.
Version TCSS 342, Winter 2006 Lecture Notes Trees Binary Trees Binary Search Trees.
CS 206 Introduction to Computer Science II 09 / 30 / 2009 Instructor: Michael Eckmann.
CSCE 3110 Data Structures & Algorithm Analysis Binary Search Trees Reading: Chap. 4 (4.3) Weiss.
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.
CM0551 Exam Prep. What are an algorithm’s time and space complexity? (2 marks) Answer: The growth rate of the algorithm’s time requirement and the computer.
Lecture 10 Trees –Definiton of trees –Uses of trees –Operations on a tree.
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 ),
Chapter 6 Binary Trees. 6.1 Trees, Binary Trees, and Binary Search Trees Linked lists usually are more flexible than arrays, but it is difficult to use.
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.
Binary Trees, Binary Search Trees RIZWAN REHMAN CENTRE FOR COMPUTER STUDIES DIBRUGARH UNIVERSITY.
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 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.
Starting at Binary Trees
Topics Definition and Application of Binary Trees Binary Search Tree Operations.
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 Chapter 7 Objectives Upon completion you will be able to: Create and implement binary search trees Understand the operation of the binary search tree.
Binary Search Trees (BSTs) 18 February Binary Search Tree (BST) An important special kind of binary tree is the BST Each node stores some information.
4-1 4 Linked List Data Structures Linked lists: singly-linked and doubly-linked. Insertion. Deletion. Searching. © 2001, D.A. Watt and D.F. Brown.
AVL Trees An AVL tree is a binary search tree with a balance condition. AVL is named for its inventors: Adel’son-Vel’skii and Landis AVL tree approximates.
Binary Tree. Some Terminologies Short review on binary tree Tree traversals Binary Search Tree (BST)‏ Questions.
ADT Binary Search Tree Ellen Walker CPSC 201 Data Structures Hiram College.
Binary Search Trees (BST)
Rooted Tree a b d ef i j g h c k root parent node (self) child descendent leaf (no children) e, i, k, g, h are leaves internal node (not a leaf) sibling.
9 Set ADTs  Set concepts  Set applications  A set ADT: requirements, contract  Implementations of sets: using member arrays, linked lists, boolean.
1 Trees General Trees  Nonrecursive definition: a tree consists of a set of nodes and a set of directed edges that connect pairs of nodes.
1 Joe Meehean. A A B B D D I I C C E E X X A A B B D D I I C C E E X X  Terminology each circle is a node pointers are edges topmost node is the root.
BINARY TREES Objectives Define trees as data structures Define the terms associated with trees Discuss tree traversal algorithms Discuss a binary.
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.
Trees By JJ Shepherd. Introduction Last time we discussed searching and sorting in a more efficient way Divide and Conquer – Binary Search – Merge Sort.
(c) University of Washington20c-1 CSC 143 Binary Search Trees.
(c) University of Washington20-1 CSC 143 Java Trees.
Binary Tree Data Structures Binary trees and binary search trees. Searching. Insertion. Deletion. Traversal. Implementation of sets using BSTs.
Binary Search Trees Chapter 7 Objectives
The Tree Data Structure
Week 6 - Wednesday CS221.
Trees.
Binary Trees, Binary Search Trees
Chapter 22 : Binary Trees, AVL Trees, and Priority Queues
Find in a linked list? first last 7  4  3  8 NULL
Trees.
Lecture 12 CS203 1.
Binary Trees, Binary Search Trees
CSC 143 Java Trees.
CSC 143 Binary Search Trees.
Trees.
Non-Linear data structures
Binary Trees, Binary Search Trees
NATURE VIEW OF A TREE leaves branches root. NATURE VIEW OF A TREE leaves branches root.
Tree (new ADT) Terminology: A tree is a collection of elements (nodes)
Presentation transcript:

10 Binary-Search-Tree Data Structure  Binary-trees and binary-search-trees  Searching  Insertion  Deletion  Traversal  Implementation of sets using binary-search-trees © 2008 David A Watt, University of Glasgow Algorithms & Data Structures (M)

10-2 Binary-trees (1)  A binary-tree consists of a header together with a number of nodes connected as follows: –Each node contains an element, plus two (possibly null) links to other nodes (its left child and right child). –The header contains a (possibly null) link to a unique node designated as the binary-tree’s root node. header D B A E C F G root node leaf nodes

10-3 Binary-trees (2)  A leaf node is one that has no children (i.e., both its links are null).  Every node, except the root node, is the left or right child of exactly one other node (its parent).  The root node has no parent; the only link to it is in the header.  The size of a binary-tree is the number of nodes (elements).  An empty binary-tree has no nodes. Its header contains a null link.

10-4 Binary-trees and subtrees  Every node has a left subtree (possibly empty) and a right subtree (possibly empty). The node’s left subtree (right subtree) consists of the node’s left child (right child) together with that child’s own children, grandchildren, etc. A’s left subtree A’s right subtree C’s left subtree C’s right subtree B’s right subtree B’s left subtree is empty D B A E C F G

10-5 Node and tree depths (1)  For any node N in a binary-tree, there is exactly one sequence of links between the root node and N.  The depth of node N is the number of links between the root node and N.  The depth of a binary-tree is the depth of its deepest node. –A binary-tree with a single node has depth 0. –By convention, an empty binary-tree has depth –1.

10-6 Node and tree depths (2)  Illustration (a balanced binary-tree): depth 0 depth 1 depth 2 D B A E C F

10-7 Node and tree depths (3)  Illustration (an unbalanced binary-tree): depth 0 depth 1 depth 2 depth 3 M K N P L J

10-8 Node and tree depths (4)  Illustration (an extremely unbalanced binary- tree): depth 4 depth 5 depth 3 depth 0 depth 1 depth 2 S T U V W X

10-9 Balanced binary-trees  A binary-tree of depth d is balanced if all nodes at depths 0, 1, …, d–2 have two children.  This implies: –Nodes at depth d–1 may have two/one/no children. –Nodes at depth d have no children (by definition). –A binary-tree of depth 0 or 1 is always balanced.  This is illustrated in the previous 3 slides.

10-10 BSTs (1)  A binary-search-tree (or BST) is a binary-tree in which the following property holds for every node: –Let elem be the element contained in the node. –The node’s left subtree (if non-empty) contains only elements less than elem. –The node’s right subtree (if non-empty) contains only elements greater than elem.

10-11 BSTs (2)  Illustrations: (a) dog cat fox lion pig rat tiger (b) pig cat dog fox lionrat tiger

10-12 BSTs (3)  An equivalent recursive definition of BSTs is also possible.  A binary-search-tree is: –empty, or –non-empty, in which case it has: a root node containing an element elem a link to a left subtree which (if non-empty) contains only elements less than elem a link to a right subtree which (if non-empty) contains only elements greater than elem.

10-13 BSTs (4)  Java class implementing BSTs: public class BST { // Each BST object is a binary-search-tree header. private BST.Node root; public BST () { // Construct an empty BST. root = null; } … BST methods (to follow)

10-14 BSTs (5)  Java class implementing BSTs (continued): ////////// Inner class ////////// private static class Node { protected Comparable element; protected Node left, right; protected Node (Comparable elem) { element = elem; left = null; right = null; } … } }

10-15 BST search (1)  Problem: Search for a given target value in a BST.  Idea: Compare the target value with the element in the root node. –If the target value is equal, the search is successful. –If the target value is less, search the left subtree. –If the target value is greater, search the right subtree. –If the subtree is empty, the search is unsuccessful.

10-16 BST search (2)  BST search algorithm: To find which if any node of a BST contains an element equal to target: 1.Set curr to the BST’s root. 2.Repeat: 2.1.If curr is null: Terminate yielding none. 2.2.Else, if target is equal to curr’s element: Terminate yielding curr. 2.3.Else, if target is less than curr’s element: Set curr to curr’s left child. 2.4.Else, if target is greater than curr’s element: Set curr to curr’s right child.

10-17 BST search (3)  Animation (successful search): To find which if any node of a BST contains an element equal to target: 1.Set curr to the BST’s root. 2.Repeat: 2.1.If curr is null, terminate yielding none. 2.2.Else, if target is equal to curr’s element, terminate yielding curr. 2.3.Else, if target is less than curr’s element, set curr to curr’s left child. 2.4.Else, if target is greater than curr’s element, set curr to curr’s right child. root dog cat fox lion pig rat tiger curr pig target To find which if any node of a BST contains an element equal to target: 1.Set curr to the BST’s root. 2.Repeat: 2.1.If curr is null, terminate yielding none. 2.2.Else, if target is equal to curr’s element, terminate yielding curr. 2.3.Else, if target is less than curr’s element, set curr to curr’s left child. 2.4.Else, if target is greater than curr’s element, set curr to curr’s right child. root dog cat fox lion pig rat tiger curr pig target To find which if any node of a BST contains an element equal to target: 1.Set curr to the BST’s root. 2.Repeat: 2.1.If curr is null, terminate yielding none. 2.2.Else, if target is equal to curr’s element, terminate yielding curr. 2.3.Else, if target is less than curr’s element, set curr to curr’s left child. 2.4.Else, if target is greater than curr’s element, set curr to curr’s right child. root dog cat fox lion pig rat tiger curr pig target To find which if any node of a BST contains an element equal to target: 1.Set curr to the BST’s root. 2.Repeat: 2.1.If curr is null, terminate yielding none. 2.2.Else, if target is equal to curr’s element, terminate yielding curr. 2.3.Else, if target is less than curr’s element, set curr to curr’s left child. 2.4.Else, if target is greater than curr’s element, set curr to curr’s right child. root dog cat fox lion pig rat tiger curr pig target

10-18 BST search (4)  Animation (unsuccessful search): To find which if any node of a BST contains an element equal to target: 1.Set curr to the BST’s root. 2.Repeat: 2.1.If curr is null, terminate yielding none. 2.2.Else, if target is equal to curr’s element, terminate yielding curr. 2.3.Else, if target is less than curr’s element, set curr to curr’s left child. 2.4.Else, if target is greater than curr’s element, set curr to curr’s right child. root dog cat fox lion pig rat tiger curr goat target To find which if any node of a BST contains an element equal to target: 1.Set curr to the BST’s root. 2.Repeat: 2.1.If curr is null, terminate yielding none. 2.2.Else, if target is equal to curr’s element, terminate yielding curr. 2.3.Else, if target is less than curr’s element, set curr to curr’s left child. 2.4.Else, if target is greater than curr’s element, set curr to curr’s right child. root dog cat fox lion pig rat tiger goat target curr To find which if any node of a BST contains an element equal to target: 1.Set curr to the BST’s root. 2.Repeat: 2.1.If curr is null, terminate yielding none. 2.2.Else, if target is equal to curr’s element, terminate yielding curr. 2.3.Else, if target is less than curr’s element, set curr to curr’s left child. 2.4.Else, if target is greater than curr’s element, set curr to curr’s right child. root dog cat fox lion pig rat tiger curr goat target To find which if any node of a BST contains an element equal to target: 1.Set curr to the BST’s root. 2.Repeat: 2.1.If curr is null, terminate yielding none. 2.2.Else, if target is equal to curr’s element, terminate yielding curr. 2.3.Else, if target is less than curr’s element, set curr to curr’s left child. 2.4.Else, if target is greater than curr’s element, set curr to curr’s right child. root dog cat fox lion pig rat tiger curr goat target To find which if any node of a BST contains an element equal to target: 1.Set curr to the BST’s root. 2.Repeat: 2.1.If curr is null, terminate yielding none. 2.2.Else, if target is equal to curr’s element, terminate yielding curr. 2.3.Else, if target is less than curr’s element, set curr to curr’s left child. 2.4.Else, if target is greater than curr’s element, set curr to curr’s right child. root dog cat fox lion pig rat tiger curr goat target

10-19 BST search (5)  BST search efficiency is clearly related to the BST’s depth. But how is its depth related to its size?  A balanced BST of depth d has at least 2 d and at most 2 d+1 –1 nodes. Therefore: Depth of balanced BST of size n = floor(log 2 n)  An unbalanced BST of depth d could have as few as d+1 nodes. Therefore: Max. depth of unbalanced BST of size n = n–1

10-20 BST search (6)  Analysis (counting comparisons): Let the BST’s size be n. If the BST has depth d, the max. no. of comparisons is d+1.  If the BST is balanced, d = floor(log 2 n): Max. no. of comparisons = floor(log 2 n) + 1 Best-case time complexity is O(log n).  If the BST is unbalanced, d  n–1: Max. no. of comparisons = n Worst-case time complexity is O(n).

10-21 BST search (7)  Implementation as a Java method (in class BST ): public BST.Node search (Comparable target) { int direction = 0; BST.Node curr = root; for (;;) { if (curr == null) return null; direction = target.compareTo(curr.element); if (direction == 0) return curr; else if (direction < 0) curr = curr.left; else curr = curr.right; } }

10-22 BST insertion (1)  Problem: Insert a new element into a BST.  We must create a new node, but we must link the new node to the BST in such a way that it remains a BST.  Idea: Proceed as if searching for that element. If the element is not already present, the search will lead to a null link. Replace that null link by a link to a leaf node containing the new element.

10-23 BST insertion (2)  BST insertion algorithm: To insert the element elem into a BST: 1.Set parent to null, and set curr to the BST’s root. 2.Repeat: 2.1.If curr is null: Replace the null link from which curr was taken (either the BST’s root or parent’s left child or parent’s right child) by a link to a newly-created leaf node with element elem Terminate. 2.2.Else, if elem is equal to curr’s element: Terminate. 2.3.Else, …

10-24 BST insertion (3)  BST insertion algorithm (continued): 2.3.Else, if elem is less than curr’s element: Set parent to curr, and set curr to curr’s left child. 2.4.Else, if elem is greater than curr’s element: Set parent to curr, and set curr to curr’s right child.

10-25 To insert the element elem into a BST: 1.Set parent to null, and set curr to the BST’s root. 2.Repeat: 2.1.If curr is null, replace the null link from which curr was taken by a link to a newly-created leaf node with element elem, and terminate. 2.2.Else, if elem is equal to curr’s element, terminate. 2.3.Else, if elem is less than curr’s element, set parent to curr and set curr to curr’s left child. 2.4.Else, if elem is greater than curr’s element, set parent to curr and set curr to curr’s right child. root fox lion rat goat elem cat To insert the element elem into a BST: 1.Set parent to null, and set curr to the BST’s root. 2.Repeat: 2.1.If curr is null, replace the null link from which curr was taken by a link to a newly-created leaf node with element elem, and terminate. 2.2.Else, if elem is equal to curr’s element, terminate. 2.3.Else, if elem is less than curr’s element, set parent to curr and set curr to curr’s left child. 2.4.Else, if elem is greater than curr’s element, set parent to curr and set curr to curr’s right child. root fox lion rat curr goat elem parent cat To insert the element elem into a BST: 1.Set parent to null, and set curr to the BST’s root. 2.Repeat: 2.1.If curr is null, replace the null link from which curr was taken by a link to a newly-created leaf node with element elem, and terminate. 2.2.Else, if elem is equal to curr’s element, terminate. 2.3.Else, if elem is less than curr’s element, set parent to curr and set curr to curr’s left child. 2.4.Else, if elem is greater than curr’s element, set parent to curr and set curr to curr’s right child. root fox lion rat curr goat elem parent cat To insert the element elem into a BST: 1.Set parent to null, and set curr to the BST’s root. 2.Repeat: 2.1.If curr is null, replace the null link from which curr was taken by a link to a newly-created leaf node with element elem, and terminate. 2.2.Else, if elem is equal to curr’s element, terminate. 2.3.Else, if elem is less than curr’s element, set parent to curr and set curr to curr’s left child. 2.4.Else, if elem is greater than curr’s element, set parent to curr and set curr to curr’s right child. root fox lion rat curr goat elem parent cat To insert the element elem into a BST: 1.Set parent to null, and set curr to the BST’s root. 2.Repeat: 2.1.If curr is null, replace the null link from which curr was taken by a link to a newly-created leaf node with element elem, and terminate. 2.2.Else, if elem is equal to curr’s element, terminate. 2.3.Else, if elem is less than curr’s element, set parent to curr and set curr to curr’s left child. 2.4.Else, if elem is greater than curr’s element, set parent to curr and set curr to curr’s right child. root cat fox lion rat curr goat elem parent goat BST insertion (4)  Animation:

10-26 BST insertion (5)  Analysis (counting comparisons): No. of comparisons is the same as for BST search.  If the BST is balanced: Max. no. of comparisons = floor(log 2 n) + 1 Best-case time complexity is O(log n).  If the BST is unbalanced: Max. no. of comparisons = n Worst-case time complexity is O(n).

10-27 BST insertion (6)  Implementation as a Java method (in class BST ): public void insert (Comparable elem) { int direction = 0; BST.Node parent = null, curr = root; for (;;) { if (curr == null) { BST.Node ins = new BST.Node(elem); if (root == null) root = ins; else if (direction < 0) parent.left = ins; else parent.right = ins; return; }

10-28 BST insertion (7)  Implementation (continued): direction = elem.compareTo(curr.element); if (direction == 0) return; parent = curr; if (direction < 0) curr = curr.left; else curr = curr.right; } }

10-29 Example: successive insertions (1)  Animation (inserting ‘lion’, ‘fox’, ‘rat’, ‘cat’, ‘pig’, ‘dog’, ‘tiger’ in that order): Initially:After inserting ‘lion’: lion After inserting ‘fox’: fox lion After inserting ‘rat’: fox lion rat After inserting ‘cat’: cat fox lion rat After inserting ‘pig’: cat fox lion pig rat After inserting ‘dog’: dog cat fox lion pig rat After inserting ‘tiger’: dog cat fox lion pig rat tiger

10-30 Example: successive insertions (2)  Animation (inserting ‘cat’, ‘dog’, ‘fox’, ‘lion’, ‘pig’, ‘rat’ in that order): Initially : After inserting ‘cat’: cat After inserting ‘dog’: dog cat After inserting ‘fox’: dog cat fox After inserting ‘lion’: dog cat fox lion After inserting ‘pig’: dog cat fox lion pig After inserting ‘rat’: dog cat fox lion pig rat

10-31 BST deletion  Problem: Delete a given element from a BST.  Idea: Search for the given element. Then delete the node containing it.  If that node has one child (or none), deleting it is easy.  But if that node has two children, we must take care not to leave two disconnected subtrees.

10-32 Deleting a given element (1)  BST deletion algorithm: To delete the element elem in a BST: 1.Set parent to null, and set curr to the BST’s root node. 2.Repeat: 2.1.If curr is null: Terminate. 2.2.Else, if elem is equal to curr’s element: Delete the topmost element in the subtree whose topmost node is curr, and let del be a link to the remaining subtree Replace the link to curr by del Terminate. 2.3.Else, …

10-33 Deleting a given element (2)  BST deletion algorithm (continued): 2.3.Else, if elem is less than curr’s element: Set parent to curr, and set curr to curr’s left child. 2.4.Else, if elem is greater than curr’s element: Set parent to curr, and set curr to curr’s right child.

10-34 Deleting a given element (3)  Animation: To delete the element elem in a BST: 1.Set parent to null, and set curr to the BST’s root node. 2.Repeat: 2.1.If curr is null, terminate. 2.2.Else, if elem is equal to curr’s element: … 2.3.Else, if elem is less than curr’s element, set parent to curr, and set curr to curr’s left child. 2.4.Else, if elem is greater than curr’s element, set parent to curr, and set curr to curr’s right child. root dog lion dog elem fox rat pigtiger To delete the element elem in a BST: 1.Set parent to null, and set curr to the BST’s root node. 2.Repeat: 2.1.If curr is null, terminate. 2.2.Else, if elem is equal to curr’s element: … 2.3.Else, if elem is less than curr’s element, set parent to curr, and set curr to curr’s left child. 2.4.Else, if elem is greater than curr’s element, set parent to curr, and set curr to curr’s right child. root dog lion dog elem fox rat pigtiger parent curr To delete the element elem in a BST: 1.Set parent to null, and set curr to the BST’s root node. 2.Repeat: 2.1.If curr is null, terminate. 2.2.Else, if elem is equal to curr’s element: … 2.3.Else, if elem is less than curr’s element, set parent to curr, and set curr to curr’s left child. 2.4.Else, if elem is greater than curr’s element, set parent to curr, and set curr to curr’s right child. root dog lion dog elem fox rat pigtiger parent curr To delete the element elem in a BST: 1.Set parent to null, and set curr to the BST’s root node. 2.Repeat: 2.1.If curr is null, terminate. 2.2.Else, if elem is equal to curr’s element: Delete the topmost element in the subtree whose topmost node is curr, and let del be a link to the remaining subtree Replace the link to curr by del Terminate. 2.3.Else, … root dog lion dog elem fox rat pigtiger parent curr To delete the element elem in a BST: 1.Set parent to null, and set curr to the BST’s root node. 2.Repeat: 2.1.If curr is null, terminate. 2.2.Else, if elem is equal to curr’s element: Delete the topmost element in the subtree whose topmost node is curr, and let del be a link to the remaining subtree Replace the link to curr by del Terminate. 2.3.Else, … root dog lion dog elem fox rat pigtiger parent curr del To delete the element elem in a BST: 1.Set parent to null, and set curr to the BST’s root node. 2.Repeat: 2.1.If curr is null, terminate. 2.2.Else, if elem is equal to curr’s element: Delete the topmost element in the subtree whose topmost node is curr, and let del be a link to the remaining subtree Replace the link to curr by del Terminate. 2.3.Else, … root dog lion dog elem fox rat pigtiger parent curr del To delete the element elem in a BST: 1.Set parent to null, and set curr to the BST’s root node. 2.Repeat: 2.1.If curr is null, terminate. 2.2.Else, if elem is equal to curr’s element: Delete the topmost element in the subtree whose topmost node is curr, and let del be a link to the remaining subtree Replace the link to curr by del Terminate. 2.3.Else, … root dog lion dog elem fox rat pigtiger

10-35 Deleting a given element (4)  Implementation as a Java method (in class BST ): public void delete (Comparable elem) { int direction = 0; BST.Node parent = null, curr = root; for (;;) { if (curr == null) return; direction = elem.compareTo(curr.element); if (direction == 0) { BST.Node del = curr.deleteTopmost(); if (curr == root) root = del; else if (curr == parent.left) parent.left = del; else parent.right = del; return;

10-36 Deleting a given element (5)  Implementation (continued): } parent = curr; if (direction 0 curr = parent.right; } }

10-37 Deleting the topmost element (1)  Problem: Delete the topmost element in a BST subtree.  Four cases to consider: A.The topmost node has no children. B.The topmost node has a right child but no left child. C.The topmost node has a left child but no right child. D.The topmost node has two children.

10-38 Deleting the topmost element (2)  Case A (topmost node has no children): The answer is an empty subtree. E.g.: lion Subtree: lion Answer:

10-39 Deleting the topmost element (3)  Case B (topmost node has a right child only): Discard the topmost node, but retain a link to its right subtree. E.g.: lion pig rat tiger Subtree: lion pig rat tiger Answer:

10-40 Deleting the topmost element (4)  Case C (topmost node has a left child only): Discard the topmost node, but retain a link to its left subtree. E.g.: lion cat fox goat Subtree: lion cat fox goat Answer:

10-41 Deleting the topmost element (5)  Case D (topmost node has two children): Copy the right subtree’s leftmost element into the topmost node, then delete the right subtree’s leftmost element. E.g.: fox cat lion rat tiger pig Subtree: fox cat pig rat tiger pig Answer:

10-42 Deleting the topmost element (6)  Algorithm: To delete the topmost element in the subtree whose topmost node is top: 1.If top has no left child: 1.1.Terminate with top’s right child as answer. 2.If top has no right child: 2.1.Terminate with top’s left child as answer. 3.If top has two children: 3.1.Set top’s element to the leftmost element in top’s right subtree. 3.2.Delete the leftmost element in top’s right subtree. 3.3.Terminate with top as answer. cases A, B cases A, C case D

10-43 Deleting the topmost element (7)  It is easy to locate the leftmost node (element) in a subtree: –If the subtree’s topmost node has no left child, the topmost node is itself the leftmost node. –If the subtree’s topmost node does have a left child, we follow left-child links until we find a node with no left child. That node is the leftmost node.

10-44 Deleting the topmost element (8)  Implementation as a Java method (in class BST.Node ): public Node deleteTopmost () { if (this.left == null) return this.right; else if (this.right == null) return this.left; else { // this node has two children this.element = this.right.getLeftmost(); this.right = this.right.deleteLeftmost(); return this; } }

10-45 Deleting the topmost element (9)  Auxiliary method (in class BST.Node ): private Comparable getLeftmost () { Node curr = this; while (curr.left != null) curr = curr.left; return curr.element; }

10-46 Deleting the topmost element (10)  Auxiliary method (in class BST.Node ): public Node deleteLeftmost () { if (this.left == null) return this.right; else { Node parent = this, curr = this.left; while (curr.left != null) { parent = curr; curr = curr.left; } parent.left = curr.right; return this; } }

10-47 Example: successive deletions  Animation (deleting ‘lion’, ‘fox’, ‘pig’ in that order): Initially: fox cat lion rat tiger dog pig After deleting ‘lion’: fox cat pig rat tiger dog pig After deleting ‘fox’: fox cat pig rat tiger dog After deleting ‘pig’: cat rat tiger dog

10-48 BSTs in practice (1)  Whether a BST is balanced or unbalanced depends on the order of insertions and deletions.  If elements are inserted in random order, the BST will probably be roughly balanced.  If elements are inserted in ascending (or descending) order, the BST will be very unbalanced.  Deletions can make a balanced BST unbalanced, or vice versa.

10-49 BSTs in practice (2)  The following trials show the results of loading a BST with n randomly-generated elements.  First trial with n = 35:

10-50 BSTs in practice (3)  Second trial with n = 35:

10-51 Binary-tree traversal  Binary-tree traversal: Visit all nodes (or elements) of the binary-tree in some predetermined order. –In-order traversal: Traverse the left subtree, then visit the root node, then traverse the right subtree. –Pre-order traversal: Visit the root node, then traverse the left subtree, then traverse the right subtree. –Post-order traversal: Traverse the left subtree, then traverse the right subtree, then visit the root node.  Note that these traversals all apply to BSTs as a special case.

10-52 In-order traversal  Binary-tree in-order traversal algorithm: To traverse, in in-order, the subtree whose topmost node is top: 1.If top is not null: 1.1.Traverse, in in-order, top’s left subtree. 1.2.Visit top. 1.3.Traverse, in in-order, top’s right subtree. 2.Terminate. fox cat lion rat tiger dog pig

10-53 Example: printing BST elements in order  Java methods (in class BST ): public void printInOrder () { printInOrder(root); } private static void printInOrder (BST.Node top) { // Print, in ascending order, all the elements in the BST // subtree whose topmost node is top. if (top != null) { printInOrder(top.left); System.out.println(top.element); printInOrder(top.right); } }

10-54 Pre-order traversal  Binary-tree pre-order traversal algorithm: To traverse, in pre-order, the subtree whose topmost node is top: 1.If top is not null: 1.1.Visit top. 1.2.Traverse, in pre-order, top’s left subtree. 1.3.Traverse, in pre-order, top’s right subtree. 2.Terminate. fox cat lion rat tiger dog pig

10-55 Post-order traversal  Binary-tree post-order traversal algorithm: To traverse, in post-order, the subtree whose topmost node is top: 1.If top is not null: 1.1.Traverse, in post-order, top’s left subtree. 1.2.Traverse, in post-order, top’s right subtree. 1.3.Visit top. 2.Terminate. fox cat lion rat tiger dog pig

10-56 Implementation of sets using BSTs (1)  Represent an (unbounded) set by: –a variable size –a BST whose elements are the set members. Empty set: 0 possible representation of {CA, MX, US} Illustration: CA MX US 3 Invariant: n BST

10-57 Implementation of sets using BSTs (2)  Note that the BST representation of a set is not necessarily unique: BE DE IT LU NL FR 6 BE DE LU NL IT FR 6 possible representations of {BE, DE, FR, IT, LU, NL}

10-58 Implementation of sets using BSTs (3)  Summary of algorithms and time complexities: OperationAlgorithmTime complexity bestworst contains BST searchO(log n)O(n) add BST insertionO(log n)O(n) remove BST deletionO(log n)O(n) equals traversal of 2 nd BST combined with searches of 1 st BST O(n' log n)O(n' n) containsAll traversal of 2 nd BST combined with searches of 1 st BST O(n' log n)O(n' n) addAll traversal of 2 nd BST combined with insertions in 1 st BST O(n' log n)O(n' n) removeAll traversal of 2 nd BST combined with deletions from 1 st BST O(n' log n)O(n' n) retainAll traversal of 2 nd BST combined with searches of 1 st BST O(n' log n)O(n' n)

10-59 More advanced search-trees  The BST’s worst-case time complexity occurs when the BST is very unbalanced.  We can avoid this by modifying the insertion and deletion algorithms to keep the search-tree approximately balanced.  This leads to: –AVL-trees –red-black-trees see Goodrich & Tamassia see Watt & Brown  The library classes java.util.TreeSet and java.util.TreeMap use red-black-trees, and thus guarantee O(log n) time complexity.