Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Binary Search Trees What are the disadvantages of using a linked list? What are the disadvantages of using an array- based list? Binary search trees.

Similar presentations


Presentation on theme: "1 Binary Search Trees What are the disadvantages of using a linked list? What are the disadvantages of using an array- based list? Binary search trees."— Presentation transcript:

1 1 Binary Search Trees What are the disadvantages of using a linked list? What are the disadvantages of using an array- based list? Binary search trees combine the dynamic allocation of linked lists with the faster searching time (using binary search) of an array-based list. The binary search tree is always sorted.

2 Binary Search Trees A search tree is a tree whose elements are organized to facilitate finding a particular element when needed A binary search tree is a binary tree that, for each node n – the left subtree of n contains elements less than the element stored in n – the right subtree of n contains elements greater than or equal to the element stored in n left subtree ’ s values < parent ’ s value < right subtree ’ s values 11 - 2Java Software Structures, 4th Edition, Lewis/Chase

3 Binary Search Trees 11 - 3Java Software Structures, 4th Edition, Lewis/Chase The children may also have 0, 1 or 2 children

4 Binary Search Trees To determine if a particular value exists in a tree – start at the root – compare target to element at current node – move left from current node if target is less than element in the current node – move right from current node if target is greater than element in the current node We eventually find the target or encounter the end of a path (target is not found) 11 - 4Java Software Structures, 4th Edition, Lewis/Chase

5 5 40 65 32 2436 30 25470 75 root How do we find a value in a BST? For example, is 25 in the tree? Use auxiliary reference ref Start at the root If the value you are searching for is equal to the value at the root you are done

6 6 40 65 32 2436 30 25470 75 root If the value you are searching for is less, move reference left If it is greater move reference right ref How can we determine that a value is not in the tree? ref Until the value is found ref Is searching for a value in a binary search tree more or less efficient than in a linked list? In an array list? Search for 25

7 Binary Search Trees Process of adding an element is similar to finding an element New elements are added as leaf nodes Start at the root, follow path dictated by existing elements until you find no child in the desired direction Then add the new element 11 - 7Java Software Structures, 4th Edition, Lewis/Chase

8 8 40 65 32 2436 30 25470 75 root To insert a value, say 17, you traverse through the tree as though searching for the value ref When a null reference is found ref How does the order of insertions affect the efficiency of the tree? Create a new node and attach it as a leaf 17

9 Binary Search Trees The particular shape of a binary search tree depends on the order in which the elements are added The shape may also be dependant on any additional processing performed on the tree to reshape it Binary search trees can hold any type of data, so long as we have a way to determine relative ordering Objects implementing the Comparable interface provide such capability 11 - 9Java Software Structures, 4th Edition, Lewis/Chase

10 Binary Search Trees Adding elements to a BST: 11 - 10Java Software Structures, 4th Edition, Lewis/Chase

11 Binary Search Trees BST operations: 11 - 11 OperationDescription addElementAdd an element to the tree removeElementRemove element from the tree removeAllOccurrencesRemove all occurrences of element from the tree removeMinRemove the minimum element in the tree removeMaxRemove the maximum element in the tree findMinReturns a reference to the minimum element in the tree FindMaxReturns a reference to the maximum element in the tree

12 /** * BinarySearchTreeADT defines the interface to a binary search tree. */ public interface BinarySearchTreeADT extends BinaryTreeADT { /** * Adds the specified element to the proper location in this tree. * @param element the element to be added to this tree */ public void addElement(T element); /** * Removes and returns the specified element from this tree. * @param targetElement the element to be removed from the tree * @return the element to be removed from the tree */ public T removeElement(T targetElement); /** * Removes all occurences of the specified element from this tree. * @param targetElement the element to be removed from the tree */ public void removeAllOccurrences(T targetElement); 11 - 12Java Software Structures, 4th Edition, Lewis/Chase

13 /** * Removes and returns the smallest element from this tree. * @return the smallest element from the tree. */ public T removeMin(); /** * Removes and returns the largest element from this tree. * @return the largest element from the tree */ public T removeMax(); /** * Returns the smallest element in this tree without removing it. * @return the smallest element in the tree */ public T findMin(); /** * Returns the largest element in this tree without removing it. * @return the largest element in the tree */ public T findMax(); } 11 - 13Java Software Structures, 4th Edition, Lewis/Chase

14 Binary Search Trees 11 - 14Java Software Structures, 4th Edition, Lewis/Chase

15 /** * LinkedBinarySearchTree implements the BinarySearchTreeADT interface * with links. * @author Lewis and Chase * @version 4.0 */ public class LinkedBinarySearchTree extends LinkedBinaryTree implements BinarySearchTreeADT { /** * Creates an empty binary search tree. */ public LinkedBinarySearchTree() { super(); } /** * Creates a binary search with the specified element as its root. * @param element to be the root of the new binary search tree */ public LinkedBinarySearchTree(T element) { super(element); if (!(element instanceof Comparable)) throw new NonComparableElementException("LinkedBinarySearchTree"); } 11 - 15Java Software Structures, 4th Edition, Lewis/Chase

16 /** * Adds the specified object to the binary search tree in the * appropriate position according to its natural order. Note that * equal elements are added to the right. * @param element the element to be added to the binary search tree */ public void addElement(T element) { if (!(element instanceof Comparable)) throw new NonComparableElementException("LinkedBinarySearchTree"); Comparable comparableElement = (Comparable )element; if (isEmpty()) root = new BinaryTreeNode (element); else { if (comparableElement.compareTo(root.getElement()) < 0) { if (root.getLeft() == null) this.getRootNode().setLeft(new BinaryTreeNode (element)); else addElement(element, root.getLeft()); } 11 - 16Java Software Structures, 4th Edition, Lewis/Chase

17 else { if (root.getRight() == null) this.getRootNode().setRight(new BinaryTreeNode (element)); else addElement(element, root.getRight()); } modCount++; } 11 - 17Java Software Structures, 4th Edition, Lewis/Chase

18 /** * Adds the specified object to the binary search tree in the * appropriate position according to its natural order. Note that * equal elements are added to the right. * @param element the element to be added to the binary search tree */ private void addElement(T element, BinaryTreeNode node) { Comparable comparableElement = (Comparable )element; if (comparableElement.compareTo(node.getElement()) < 0) { if (node.getLeft() == null) node.setLeft(new BinaryTreeNode (element)); else addElement(element, node.getLeft()); } else { if (node.getRight() == null) node.setRight(new BinaryTreeNode (element)); else addElement(element, node.getRight()); } 11 - 18Java Software Structures, 4th Edition, Lewis/Chase

19 BST Element Removal Removing a target in a BST is not as simple as that for linear data structures After removing the element, the resulting tree must still be valid Three distinct situations must be considered when removing an element – The node to remove is a leaf – The node to remove has one child – The node to remove has two children 11 - 19Java Software Structures, 4th Edition, Lewis/Chase

20 BST Element Removal 11 - 20Java Software Structures, 4th Edition, Lewis/Chase Situation 1 Situation 2 Situation 3

21 BST Element Removal Dealing with the situations – Node is a leaf: it can simply be deleted – Node has one child: the deleted node is replaced by the child – Node has two children: an appropriate node is found lower in the tree and used to replace the node Good choice: inorder successor (node that would follow the removed node in an inorder traversal) The inorder successor is guaranteed not to have a left child Thus, removing the inorder successor to replace the deleted node will result in one of the first two situations (it’s a leaf or has one child) 11 - 21Java Software Structures, 4th Edition, Lewis/Chase

22 22 The node we are removing may be a leaf Notice: the node we are deleting may be a right child or a left child of its parent The node may also be the root (no parent) 40 6532 24 36 25470 75 root 30 parent node In this case we must make the parent of the node refer to null garbage collection

23 23 40 6532 24 36 25470 75 root The node we are removing may have one child Notice: the node we are deleting may be a right child with a right child, a right child with a left child a left child with a left child, a left child with a right child The node may also be the root (no parent), in which case you make the child (left or right) the root 30 parent node 31 garbage collection In this case we must make the “ grandparent ” refer to the child

24 24 40 65 32 2036 30 254 70 75 222 23 What if the node we are removing has two children? root node parent Can we move one of the node ’ s children up to take its place? What if the children have two children?

25 25 40 65 32 2036 30 254 70 75 222 23 The solution is to find the node ’ s successor root node parent successor

26 26 The solution is to find the node ’ s successor And replace the node ’ s value with the successor ’ s value 40 65 32 36 30 254 70 75 222 23 root node parent successor 20 22

27 27 40 6532 22 36 30 25470 75 2 23 The solution is to find the node ’ s successor root node And replace the node ’ s value with the successor ’ s value Make the successor's parent refer to its child parent successor 22 Remove the successor

28 /** * Removes the first element that matches specified target element from * the binary search tree and returns a reference to it. Throws * ElementNotFoundException if target is not in the binary search tree. * @param targetElement the element being sought in the binary search tree * @throws ElementNotFoundException if the target element is not found */ public T removeElement(T targetElement) throws ElementNotFoundException { T result = null; if (isEmpty()) throw new ElementNotFoundException("LinkedBinarySearchTree"); else { BinaryTreeNode parent = null; if (((Comparable )targetElement).equals(root.element)) { result = root.element; BinaryTreeNode temp = replacement(root); if (temp == null) root = null; 11 - 28Java Software Structures, 4th Edition, Lewis/Chase

29 else { root.element = temp.element; root.setRight(temp.right); root.setLeft(temp.left); } modCount--; } else { parent = root; if (((Comparable)targetElement).compareTo(root.element) < 0) result = removeElement(targetElement, root.getLeft(), parent); else result = removeElement(targetElement, root.getRight(), parent); } return result; } 11 - 29Java Software Structures, 4th Edition, Lewis/Chase

30 /** * Removes the first element that matches the specified target * element from the binary search tree and returns a reference to * it. Throws a ElementNotFoundException if the specified target * element is not found in the binary search tree. * @param targetElement the element being sought in the binary search tree * @param node the node from which to search * @param parent the parent of the node from which to search * @throws ElementNotFoundException if the target element is not found */ private T removeElement(T targetElement, BinaryTreeNode node, BinaryTreeNode parent) throws ElementNotFoundException { T result = null; if (node == null) throw new ElementNotFoundException("LinkedBinarySearchTree"); else { if (((Comparable )targetElement).equals(node.element)) { result = node.element; BinaryTreeNode temp = replacement(node); if (parent.right == node) parent.right = temp; 11 - 30Java Software Structures, 4th Edition, Lewis/Chase

31 else parent.left = temp; modCount--; } else { parent = node; if (((Comparable)targetElement).compareTo(node.element) < 0) result = removeElement(targetElement, node.getLeft(), parent); else result = removeElement(targetElement, node.getRight(), parent); } return result; } 11 - 31Java Software Structures, 4th Edition, Lewis/Chase

32 /** * Returns a reference to a node that will replace the one * specified for removal. In the case where the removed node has * two children, the inorder successor is used as its replacement. * @param node the node to be removed * @return a reference to the replacing node */ private BinaryTreeNode replacement(BinaryTreeNode node) { BinaryTreeNode result = null; if ((node.left == null) && (node.right == null)) result = null; else if ((node.left != null) && (node.right == null)) result = node.left; else if ((node.left == null) && (node.right != null)) result = node.right; else { BinaryTreeNode current = node.right; BinaryTreeNode parent = node; 11 - 32Java Software Structures, 4th Edition, Lewis/Chase

33 while (current.left != null) { parent = current; current = current.left; } current.left = node.left; if (node.right != current) { parent.left = current.right; current.right = node.right; } result = current; } return result; } 11 - 33Java Software Structures, 4th Edition, Lewis/Chase

34 BST Element Removal 11 - 34Java Software Structures, 4th Edition, Lewis/Chase

35 /** * Removes elements that match the specified target element from * the binary search tree. Throws a ElementNotFoundException if * the sepcified target element is not found in this tree. * @param targetElement the element being sought in the binary search tree * @throws ElementNotFoundException if the target element is not found */ public void removeAllOccurrences(T targetElement) throws ElementNotFoundException { removeElement(targetElement); try { while (contains((T)targetElement)) removeElement(targetElement); } catch (Exception ElementNotFoundException) { } 11 - 35Java Software Structures, 4th Edition, Lewis/Chase

36 /** * Removes the node with the least value from the binary search * tree and returns a reference to its element. Throws an * EmptyCollectionException if this tree is empty. * @return a reference to the node with the least value * @throws EmptyCollectionException if the tree is empty */ public T removeMin() throws EmptyCollectionException { T result = null; if (isEmpty()) throw new EmptyCollectionException("LinkedBinarySearchTree"); else { if (root.left == null) { result = root.element; root = root.right; } else { BinaryTreeNode parent = root; BinaryTreeNode current = root.left; 11 - 36Java Software Structures, 4th Edition, Lewis/Chase

37 while (current.left != null) { parent = current; current = current.left; } result = current.element; parent.left = current.right; } modCount--; } return result; } 11 - 37Java Software Structures, 4th Edition, Lewis/Chase

38 BST Element Removal Removing the minimum element: 11 - 38Java Software Structures, 4th Edition, Lewis/Chase


Download ppt "1 Binary Search Trees What are the disadvantages of using a linked list? What are the disadvantages of using an array- based list? Binary search trees."

Similar presentations


Ads by Google