1 Binary Search Trees (BSTs) What is a Binary search tree? Why Binary search trees? Binary search tree implementation Insertion in a BST Deletion from.

Slides:



Advertisements
Similar presentations
COL 106 Shweta Agrawal and Amit Kumar
Advertisements

Comp 122, Spring 2004 Binary Search Trees. btrees - 2 Comp 122, Spring 2004 Binary Trees  Recursive definition 1.An empty tree is a binary tree 2.A node.
Jan Binary Search Trees What is a search binary tree? Inorder search of a binary search tree Find Min & Max Predecessor and successor BST insertion.
Binary Search Trees Many of the slides are from Prof. Plaisted’s resources at University of North Carolina at Chapel Hill.
CS 332: Algorithms Binary Search Trees. Review: Dynamic Sets ● Next few lectures will focus on data structures rather than straight algorithms ● In particular,
ALGORITHMS THIRD YEAR BANHA UNIVERSITY FACULTY OF COMPUTERS AND INFORMATIC Lecture six Dr. Hamdy M. Mousa.
Binary Search Trees Azhar Maqsood School of Electrical Engineering and Computer Sciences (SEECS-NUST)
Binary Search Trees Comp 550.
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
Binary Trees, Binary Search Trees CMPS 2133 Spring 2008.
AVL Search Trees Inserting in an AVL tree Insertion implementation Deleting from an AVL tree.
Binary Trees, Binary Search Trees COMP171 Fall 2006.
Lecture 13 AVL Trees King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department.
1 Trees Definition of a Tree Tree Terminology Importance of Trees Implementation of Trees Binary Trees –Definition –Full and Complete Binary Trees –Implementation.
1 Binary Search Trees (BST) What is a Binary search tree? Why Binary search trees? Binary search tree implementation Insertion in a BST Deletion from a.
BST Data Structure A BST node contains: A BST contains
1 Trees What is a Tree? Tree terminology Why trees? What is a general tree? Implementing trees Binary trees Binary tree implementation Application of Binary.
Lec 15 April 9 Topics: l binary Trees l expression trees Binary Search Trees (Chapter 5 of text)
1 Binary Search Trees (BST) What is a Binary search tree? Why Binary search trees? Binary search tree implementation Insertion in a BST Deletion from a.
AVL Search Trees What is an AVL Tree? AVL Tree Implementation. Why AVL Trees? Rotations. Insertion into an AVL tree Deletion from an AVL tree.
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
David Luebke 1 7/2/2015 ITCS 6114 Binary Search Trees.
1 Trees What is a Tree? Tree terminology Why trees? General Trees and their implementation N-ary Trees N-ary Trees implementation Implementing trees Binary.
Marc Smith and Jim Ten Eyck
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.
Version TCSS 342, Winter 2006 Lecture Notes Trees Binary Trees Binary Search Trees.
CSCE 3110 Data Structures & Algorithm Analysis Binary Search Trees Reading: Chap. 4 (4.3) Weiss.
Chapter 19 - basic definitions - order statistics ( findkth( ) ) - balanced binary search trees - Java implementations Binary Search Trees 1CSCI 3333 Data.
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:
Chapter 12. Binary Search Trees. Search Trees Data structures that support many dynamic-set operations. Can be used both as a dictionary and as a priority.
© 2011 Pearson Addison-Wesley. All rights reserved 11 B-1 Chapter 11 (continued) Trees.
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 Trees, Binary Search Trees RIZWAN REHMAN CENTRE FOR COMPUTER STUDIES DIBRUGARH UNIVERSITY.
Chapter 19: Binary Trees Java Programming: Program Design Including Data Structures Program Design Including Data Structures.
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.
Binary SearchTrees [CLRS] – Chap 12. What is a binary tree ? A binary tree is a linked data structure in which each node is an object that contains following.
Trees, Binary Trees, and Binary Search Trees COMP171.
Binary Search Trees (10.1) CSE 2011 Winter November 2015.
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.
Topic 19 Binary Search Trees "Yes. Shrubberies are my trade. I am a shrubber. My name is 'Roger the Shrubber'. I arrange, design, and sell shrubberies."
Data Structures Haim Kaplan and Uri Zwick November 2012 Lecture 3 Dynamic Sets / Dictionaries Binary Search Trees.
Lec 15 Oct 18 Binary Search Trees (Chapter 5 of text)
Preview  Graph  Tree Binary Tree Binary Search Tree Binary Search Tree Property Binary Search Tree functions  In-order walk  Pre-order walk  Post-order.
David Stotts Computer Science Department UNC Chapel Hill.
CISC 235 Topic 3 General Trees, Binary Trees, Binary Search 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)
ADT Binary Search Tree Ellen Walker CPSC 201 Data Structures Hiram College.
Lecture 10COMPSCI.220.FS.T Binary Search Tree BST converts a static binary search into a dynamic binary search allowing to efficiently insert and.
CSE 2331/5331 Topic 8: Binary Search Tree Data structure Operations.
1 the BSTree class  BSTreeNode has same structure as binary tree nodes  elements stored in a BSTree are a key- value pair  must be a class (or a struct)
CS6045: Advanced Algorithms Data Structures. Dynamic Sets Next few lectures will focus on data structures rather than straight algorithms In particular,
Binary Search Trees What is a binary search tree?
BST Trees
Binary Search Tree Chapter 10.
Lecture 22 Binary Search Trees Chapter 10 of textbook
Trees.
Binary Trees, Binary Search Trees
Chapter 22 : Binary Trees, AVL Trees, and Priority Queues
Lec 12 March 9, 11 Mid-term # 1 (March 21?)
Binary Search Trees (BST)
CS6045: Advanced Algorithms
Binary Trees, Binary Search Trees
Topic 6: Binary Search Tree Data structure Operations
Trees.
Binary Search Trees Comp 122, Spring 2004.
Binary Trees, Binary Search Trees
Presentation transcript:

1 Binary Search Trees (BSTs) What is a Binary search tree? Why Binary search trees? Binary search tree implementation Insertion in a BST Deletion from a BST TreeSort BSTs as Priority Queues

2 Binary Search Tree (Definition) A binary search tree (BST) is a binary tree that is empty or that satisfies the BST ordering property: 1.The key of each node is greater than each key in the left subtree, if any, of the node. 2.The key of each node is less than each key in the right subtree, if any, of the node. Thus, each key in a BST is unique. Examples: AA B C D Note: The literature contains three other definitions for BST that allow duplicate keys in a BST. For any node x: key[leftSubtree(x)]  key[x] < key[rightSubtree(x)] key[leftSubtree(x)] < key[x]  key[rightSubtree(x)] key[leftSubtree(x)]  key[x]  key[rightSubtree(x)] We will not use any of these definitions in this course.

3 Binary Search Tree (Definition) (Contd.) A common misunderstanding is that the BST ordering property is only between parents and children, rather than all the values in left and right subtrees. It is a common error to interpret the BST ordering property as: 1.The key of each node is greater than the key of the left child of that node, if any. 2.The key of each node is less than the key of the right child of that node, if any Example: The above is not a BST because both 22 and 25 cannot be on the left subtree of 20; however each node satisfies the BST property with respect to its two children.

4 Why BSTs? TraversalDeletionInsertion Retrieval or Search Data Structure O(n)O(log n) BST O(n) O(log n) (using Binary Search) Sorted Array O(n) O(1)O(n)Unsorted Array O(n) Sorted Linked List O(n) O(1)O(n)LinkedList 1. BSTs provide good logarithmic time performance in the best and average cases. Average case complexities of using linear data structures compared to BSTs: Note: BST worst execution time for each of the above operations is O(n) when the tree is linear

5 Why BSTs? (Contd.) 2. Binary Search Trees (BSTs) are an important data structure for dynamic sets and Dictionaries: Each element is an Association object having a Comparable key and an Object value Dynamic sets support queries such as: Search(x), Minimum(), Maximum(), Successor(x), Predecessor(x) They also support modifying operations like: Insert(x) and Delete(x) 3. BSTs can be used to implement priority queues 4. BSTs are used in TreeSort

6 Binary Search Tree Implementation The BinarySearchTree class inherits the instance variables key, left, and right of the BinaryTree class: public class BinarySearchTree extends BinaryTree implements SearchableContainer { private BinarySearchTree getLeftBST(){ return (BinarySearchTree) getLeft( ) ; } private BinarySearchTree getRightBST( ){ return (BinarySearchTree) getRight( ) ; } //... }

7 Binary Search Tree Implementation: find The recursive find method of the BinarySearchTree class: public Comparable find(Comparable target) { if(isEmpty()) return null; Comparable currentKey = (Comparable) key; int comparison = target.compareTo(currentKey); if(comparison == 0) return currentKey; else if(comparison < 0) return getLeftBST().find(target); else return getRightBST().find(target); }

8 Binary Search Tree Implementation: findIterative The iterative find method of the BinarySearchTree class: public Comparable findIterative(Comparable target){ if(isEmpty()) return null; BinarySearchTree tree = this; while(!tree.isEmpty()){ Comparable currentKey = (Comparable) key; int comparison = currentKey.compareTo(target); if(comparison == 0) return currentKey; else if(comparison < 0) tree = tree.getLeftBST(); else tree = tree.getRightBST(); } return null; }

9 Binary Search Tree Implementation: findMin The findMin method of the BinarySearchTree class: By the BST ordering property, the minimum key is the key of the left-most node that has an empty left-subtree. public Comparable findMin() { if(isEmpty()) return null; if(getLeftBST().isEmpty()) return (Comparable)getKey(); else return getLeftBST().findMin(); } Exercise: Write the iterative findMin

10 Binary Search Tree Implementation: findMax The findMax method of the BinarySearchTree class: By the BST ordering property, the maximum key is the key of the right-most node that has an empty right-subtree public Comparable findMax() { if(isEmpty()) return null; if(getRightBST().isEmpty()) return (Comparable)getKey(); else return getRightBST().findMax(); } Exercise: Write the iterative findMax

11 Binary Search Tree Implementation: findSuccessor The successor of a key x is the smallest key greater than x. If(x has a non-empty right subtree) Successor of x is the minimum value in the right subtree of x else{ if(x is maximum value in tree) x has no successor else successor is smallest ancestor of x that is greater than x } successorkey No successor40 Example:

12 Binary Search Tree Implementation: findSuccessor (Contd.) public Comparable findSuccessor(Comparable x){ if(isEmpty()) throw new IllegalArgumentException("Tree is empty"); else return findSuccessor(x, (Comparable)getKey()); } private Comparable findSuccessor(Comparable x, Comparable successor){ if(isEmpty()) throw new IllegalArgumentException(x + " is not in tree"); Comparable currentKey = (Comparable)getKey(); int comparison = x.compareTo(currentKey); if(comparison == 0){ if(!getRightBST().isEmpty()) return getRightBST().findMin(); else if(getRightBST().isEmpty() && successor.compareTo(x) < 0) // x is max value in tree throw new IllegalArgumentException(x + " has no successor"); else return successor; } else if(comparison < 0) return getLeftBST().findSuccessor(x, currentKey); else return getRightBST().findSuccessor(x, successor); }

13 Binary Search Tree Implementation: findPredecessor The predecessor of a key x is the largest key smaller than x. If(x has a non-empty left subtree) predecessor of x is the maximum value in the left subtree of x else{ if(x is minimum value in tree) x has no predecessor else predecessor is the last ancestor of x that is smaller than x (on the path from root to the node x) } predecessorkey No predecessor Example:

14 Binary Search Tree Implementation: findPredecesor (Contd.) public Comparable findPredecessor(Comparable x){ if(isEmpty()) throw new IllegalArgumentException("Tree is empty"); else if(x.equals(getKey()) && getLeftBST().isEmpty()) throw new IllegalArgumentException(x + " has no predecessor"); else return findPredecessor(x, (Comparable)getKey()); } private Comparable findPredecessor(Comparable x, Comparable predecessor){ if(isEmpty()) throw new IllegalArgumentException(x + " is not in tree"); Comparable currentKey = (Comparable)getKey(); int comparison = x.compareTo(currentKey); if(comparison == 0){ if(!getLeftBST().isEmpty()) return getLeftBST().findMax(); else if(getLeftBST().isEmpty() && predecessor.compareTo(x) > 0) // x is min value in tree throw new IllegalArgumentException(x + " has no predecessor"); else return predecessor; } else if(comparison > 0) return getRightBST().findPredecessor(x, currentKey); else return getLeftBST().findPredecessor(x, predecessor); }

15 Insertion in a BST By the BST ordering property, a new node is always inserted as a leaf node. The insert method, given in the next page, recursively finds an appropriate empty subtree to insert the new key. It then transforms this empty subtree into a leaf node by invoking the attachKey method: public void attachKey(Object obj) { if(!isEmpty()) throw new InvalidOperationException(); else { key = obj; left = new BinarySearchTree(); right = new BinarySearchTree(); }

16 Insertion in a BST (Contd.) public void insert(Comparable comparable){ if(isEmpty()) attachKey(comparable); else { Comparable key = (Comparable) getKey(); if(comparable.compareTo(key)==0) throw new IllegalArgumentException("duplicate key"); else if (comparable.compareTo(key)<0) getLeftBST().insert(comparable); else getRightBST().insert(comparable); }

17 Deletion in a BST There are three cases: 1.The node to be deleted is a leaf node. 2.The node to be deleted has one non-empty child. 3.The node to be deleted has two non-empty children.

18 CASE 1: Deleting a Leaf Node Convert the leaf node into an empty tree by using the detachKey method: // In Binary Tree class public Object detachKey( ){ if(! isLeaf( )) throw new InvalidOperationException( ) ; else { Object obj = key ; key = null ; left = null ; right = null ; return obj ; } Example: Delete 5

19 CASE 2: Deleting a one-child node CASE 2: THE NODE TO BE DELETED HAS ONE NON-EMPTY CHILD (a) The right subtree of the node x to be deleted is empty. Example: Delete target temp 6 target // Let target be a reference to the node x. BinarySearchTree temp = target.getLeftBST(); target.key = temp.key; target.left = temp.left; target.right = temp.right; temp = null;

20 CASE 2: Deleting a one-child node (Cont’d) (b) The left subtree of the node x to be deleted is empty. Example: Delete target temp target 14 9 // Let target be a reference to the node x. BinarySearchTree temp = target.getRightBST(); target.key = temp.key; target.left = temp.left; target.right = temp.right; temp = null;

21 CASE 3: DELETING A NODE THAT HAS TWO NON-EMPTY CHILDREN DELETION BY COPYING: METHOD#1 Copy the minimum key in the right subtree of x to the node x, then delete the one-child or leaf-node with this minimum key. Example: Delete

22 CASE 3: DELETING A NODE THAT HAS TWO NON-EMPTY CHILDREN (Contd.) DELETION BY COPYING: METHOD#2 Copy the maximum key in the left subtree of x to the node x, then delete the one-child or leaf-node with this maximum key. Example: Delete

23 Deletion by Copying: Method#1 implementation // find the minimum key in the right subtree of the target node Comparable min = target.getRightBST().findMin(); // copy the minimum value to the target target.key = min; // delete the one-child or leaf node having the min target.getRightBST().withdraw(min); Note: All the different cases for deleting a node are handled in the withdraw (Comparable key) method of BinarySearchTree class

24 Tree Sort Any of the following in-order traversal behaviour of BST can be used to implement a sorting algorithm on an array of distinct elements: The in-order traversal of a BST visits the nodes of the tree in increasing sorted order The reverse in-order traversal of a BST visits the nodes in decreasing sorted order This algorithm is called TreeSort In-order Traversal: 4, 7, 9, 10, 15, 20, 25, 30, 32, 35, 40 Reverse in-order Traversal: 40, 35, 32, 30, 25, 20, 15, 10, 9, 7, 4 Example:

25 Tree Sort (Contd.) public static void treeSort(int[] x){ BinarySearchTree tree = buildBST(x); if(tree == null) throw new IllegalArgumentException("Error: Duplicate keys"); else{ int[] index = {0}; // need to pass index by reference tree.treeSort(x, index); } private void treeSort(int[] x, int[] index){ if(isEmpty()) return; else{ getLeftBST().treeSort(x, index); int k = index[0]; x[k] = (Integer) getKey(); index[0] = k + 1; getRightBST().treeSort(x, index); } TreeSort algorithm: Insert the array elements in a BST Perform an in-order traversal on the BST, storing each visited value in the corresponding array location

26 Tree Sort (Contd.) private static BinarySearchTree buildBST(int[ ] x){ // x must have distinct values BinarySearchTree tree = new BinarySearchTree( ); for(int k = 0; k < x.length; k++){ try{ tree.insert(new Integer(x[k])); } catch(IllegalArgumentException e){ tree = null; } return tree; }

27 Tree Sort (Contd.) public static void treeSort(int[ ] x){ BinarySearchTree tree = buildBST(x); if(tree == null) throw new IllegalArgumentException("Error: Duplicate keys"); else{ for(int k = 0; k < x.length; k++){ Comparable min = tree.findMin(); x[k] = (Integer) min; tree.withdraw(min); } An alternative TreeSort algorithm is: Insert the array elements in a BST for(int k = 0; k < array.length; k++) array[k] = bst.Min(); bst.exractMin(); }

28 Tree Sort (Contd.) Adding items to a binary search tree is on average an O(log n) process, so adding n items is an O(n log n) process. But adding an item to an unbalanced binary tree needs O(n) time in the worst- case, when the tree resembles a linked list (degenerate tree), causing a worst case of O(n 2 ) for this sorting algorithm. The worst case scenario happens when Tree Sort algorithm sorts an already sorted array. This would make the time needed to insert all elements into the binary tree O(n 2 ). The worst-case behaviour can be improved upon by using a Self-balancing binary search tree such as AVL tree. Using such a tree, the algorithm has an O(n log n) worst-case performance.

29 BSTs as Priority Queues By using insert and withdrawMax or WithdrawMin a BST can be used as a priority queue in which the keys of the elements are distinct.