class: center, middle, title-slide # CSCI-UA 102 ## Data Structures
## Binary Search Trees (BST) .author[ Instructor: Joanna Klukowska
] .license[ Copyright 2020 Joanna Klukowska. Unless noted otherwise all content is released under a
[Creative Commons Attribution-ShareAlike 4.0 International License](https://creativecommons.org/licenses/by-sa/4.0/).
Background image by Stewart Weiss
] --- layout:true template: default name: section class: inverse, middle, center --- layout:true template: default name: breakout class: breakout, middle --- layout:true template:default name:slide class: slide .bottom-left[© Joanna Klukowska. CC-BY-SA.] --- template: section # Binary Search Tree (BST) Introduction --- template: slide ## BST .left-column2[ A binary search tree (BST) is a binary tree with an ordering property: for every node, - all values in its left subtree are smaller than the node's value, and - all values in its right subtree are larger than the node's value. ] -- .center[
.small[Triangles are used to denote subtrees; circles are used to denote nodes.] ] -- .below-column2[.smaller[
__What about duplicate values?__ ]] -- .smaller[ - In this deck's definition, values are strictly ordered, so duplicates are not allowed. - An implementation that supports duplicates must define a consistent placement rule for equal values. ] --- name:bst-examples ## BST Examples Is this a BST? --- template:bst-examples .center[
] -- .center[.blue[.large[ ✓ ]]] --- template:bst-examples .center[
] -- .center[.blue[.large[ ✓ ]]] --- template:bst-examples .center[
] -- .center[.red[.large[ ✗ ]]] --- template:bst-examples .center[
] -- .center[.blue[.large[ ✓ ]]] --- template:bst-examples .center[
] -- .center[.green[.large[ ? ]]] -- .center[If the ordering of values is alphabetical, then .red[.large[ ✗ ]]] -- .center[If the ordering of values is by number of characters with ties resolved alphabetically, then .blue[.large[ ✓ ]]] --- template:section # BST Node --- ## BST Node A BST node has the same structure as a binary-tree node: -- .left-column2[ ``` class BSTNode { E data; BSTNode left; BSTNode right; // constructors // and methods as needed ... } ``` ]
-- .below-column2[ ]
Java generics also allow us to ensure that a node (and, later, the tree) can only be instantiated with types that can be compared. Otherwise, we cannot determine where values should be placed in the tree. --- ## Generic BST class - take 1 .smaller[ ```java class BST < T extends Comparable
> { ... private class BSTNode { T data; BSTNode left; BSTNode right; public BSTNode ( T data ) { this.data = data; } public BSTNode (T data, BSTNode left, BSTNode right ) { this.data = data; this.left = left; this.right = right; } } ... } ``` ] - `T` in this definition serves the same role as `E`; in fact, either letter can be used. - `T extends Comparable
` requires that the type used in the node implement the `Comparable
` interface. This is an additional requirement that we can place on a generic type. --- ## Generic BST class - take 2 .smaller[ ```java class BST < T extends Comparable
> { ... private class BSTNode implements Comparable < BSTNode > { T data; BSTNode left; BSTNode right; public BSTNode ( T data ) { this.data = data; } public BSTNode (T data, BSTNode left, BSTNode right ) { this.data = data; this.left = left; this.right = right; } public int compareTo ( BSTNode other ) { return this.data.compareTo ( other.data ); } } ... } ``` ] - We can make the node comparable by implementing the `Comparable
` interface. This allows us to compare nodes directly without having to inspect their data. --- template: section # Searching for an Item in a BST --- name:find ## `find` in a BST Looking for a value in a BST should remind us of searching a sorted list using binary search. At each step, we decide whether _to go left_ or _to go right_. Once we make that decision, we never need to go back. --- template:find .center[
] --- template:find .center[
When we look for __58__, we'll first compare it to the value in the root of the tree: __55__. ] --- template:find .center[
Since 55 < 58, we know that the value we are looking for cannot be in the left subtree, so we eliminate that entire subtree and explore the right subtree by comparing 58 to its root: 78. ] --- template:find .center[
Since 78 > 58, we know that the value we are looking for cannot be in the right subtree, so we eliminate that entire subtree and explore the left subtree by comparing 58 to its root: 63. ] --- template:find .center[
63 > 58, so we can eliminate the right subtree and explore the left subtree ... ] --- template:find .center[
63 > 58, so we can eliminate the right subtree and explore the left subtree ...
whose root is the value that we were searching for. ] --- template:find .center[
] .center80[ To look for __40__, we will follow a similar procedure: ] --- template:find .center[
] .center80[ To look for __40__: 55 > 40, so move left. ] --- template:find .center[
] .center80[ 55 > 40, so move left; 30 < 40, so move right. ] --- template:find .center[
] .center80[ 55 > 40, so move left; 30 < 40, so move right; 42 > 40, so move left. ] --- template:find .center[
] .center80[ 55 > 40, so move left; 30 < 40, so move right; 42 > 40, so move left; 35 < 40, so move right. ] --- template:find .center[
] .center80[ 55 > 40, so move left; 30 < 40, so move right; 42 > 40, so move left; 35 < 40, so move right.
Since there is nothing else to explore, we know __40 is not in this tree__. ] --- ## `find` in a BST - Pseudocode ``` boolean find ( T data ) { return find ( data, root ) } boolean find ( T data, BSTNode node ) if node == null return false else if (data.compareTo(node.data) < 0) return find( data, node.left ) else if (data.compareTo(node.data) > 0) return find (data, node.right ) else return true ``` -- - What is the performance of this operation? -- **O(H)** where H is the height of the tree -- .smaller[ Since the height of the tree could be as much as N, i.e., H = O(N), the performance of this function could be as bad as linear, O(N) in the worst case. But stating it as O(H) gives us a more accurate description that applies to the best, the average and the worst case performance. Note: The performance in this case depends on the shape of the tree. The same algorithm can take O(N) or O(log N) time for a find operation, depending on the shape of the tree. ] --- template: section # Adding and Removing in a BST --- name:add ## `add` to a BST To add a new value to a BST, we first find a location for it (using the same algorithm as `find`) and then attach it there. --- template:add .center[
] --- template:add .center[
To add 13, we figure out that it should become the left child of 20. ] --- template:add .center[
To add 13, we figure out that it should become the left child of 20. ] --- template:add .center[
To add 65, we figure out that it should become the left child of 70. ] --- template:add .center[
To add 65, we figure out that it should become the left child of 70. ] -- .center[Could it also be a right child of 58? {{content}}] -- NO --- template:add .center[
To add 65, we figure out that it should become the right child of 97. ] --- template:add .center[
To add 65, we figure out that it should become the left child of 97. ] --- template:add .center[
To add 75, we figure out that it should become the right child of 72. ] --- template:add .center[
To add 75, we figure out that it should become the right child of 72. ] --- template:add .center[
.red[__Can you think of any value for which there is more than one possible location in the tree?__] ] -- .center[__There aren't any!__ The place for a new value is completely determined
by the values that are currently in the tree. ] --- name:remove ## `remove` from a BST To remove a value from a BST, we first find it in the tree (using the same algorithm as `find`) and then, if it exists, we detach it from the tree. --- template:remove .center[
] --- template:remove .center[
] --- template:remove .center[
] .center80[ To remove 35, we first locate it in the tree ] --- template:remove .center[
] .center80[ To remove 35, we first locate it in the tree and then set the reference from its parent to `null` - effectively detaching it from the tree. ] --- template:remove .center[
] --- template:remove .center[
] --- template:remove .center[
] .center80[ To remove 70, we first locate it in the tree {{content}} ] -- (but we cannot just set its parent's reference to `null`, because we would lose 72 in the process) --- template:remove .center[
] .center80[ To remove 70, we first locate it in the tree and then set its parent's reference to point to 72. ] --- template:remove .center[
] --- template:remove .center[
] --- template:remove .center[
] --- template:remove .center[
] .center80[ To remove 55, we first locate it in the tree (that is easy) {{content}} ] -- but we cannot use either of the previous methods—setting the parent's reference to `null` or to one of 55's children—because 55 has two children. --- template:remove .center[
] .center80[ To remove 55, we first locate it in the tree (that is easy) and then __look for a value that could be placed in its position without disturbing the order of the rest of the tree__. {{content}} ] -- It turns out there are two such values: 42 (55's inorder predecessor) and 58 (55's inorder successor). --- template:remove .center[
] .center80[ To remove 55, we first locate it in the tree (that is easy) and then look for a value that could be placed in its position without disturbing the order of the rest of the tree. To use 42, we replace the value of 55 with 42 and then __remove 42 from the left subtree__. ] --- template:remove .center[
] .center80[ To remove 55, we first locate it in the tree (that is easy) and then look for a value that could be placed in its position without disturbing the order of the rest of the tree. To use 42, we replace the value of 55 with 42 and then __remove 42 from the left subtree__. ] --- template:remove .center[
] .center80[ To remove 55, we first locate it in the tree (that is easy) and then look for a value that could be placed in its position without disturbing the order of the rest of the tree. To use 58, we replace the value of 55 with 58 and then __remove 58 from the right subtree__. ] --- template:remove .center[
] .center80[ To remove 55, we first locate it in the tree (that is easy) and then look for a value that could be placed in its position without disturbing the order of the rest of the tree. To use 58, we replace the value of 55 with 58 and then __remove 58 from the right subtree__. ] --- ## `remove` from a BST There are three cases when removing a node from a BST: -- - Removing a leaf: disconnect it from the tree by setting its parent's reference to `null`. -- - Removing a node with one child (one subtree): disconnect it from the tree by setting its parent's reference to point to its only child (left or right). -- - Removing a node with two children (two subtrees): - find its inorder predecessor (or successor), - use that value to replace the value being removed, - remove the predecessor from the left subtree (or the successor from the right subtree). -- ----- In the last case, we need to be able to find an inorder predecessor or an inorder successor of a given value. How can we do this? -- .left-column2[ ``` T getPredecessor ( BSTNode node ) BSTNode current = node.left while (current.right != null ) current = current.right return current.data ``` ] -- .right-column2[ ``` T getSuccessor ( BSTNode node ) BSTNode current = node.right while (current.left != null ) current = current.left return current.data ``` ] --- template:section # Examples and Things to Think About --- ## `min` and `max` for a BST Provide an algorithm that finds and returns the smallest and largest values in a binary search tree. __Challenging:__ Provide an algorithm that returns the nth-smallest value. You can assume that n is smaller than the number of nodes in the tree. --- ## Iterative `find` We looked at a recursive algorithm for the `find` method. Can you implement an equivalent method iteratively? Do you need an additional data structure to keep track of explored vs. unexplored branches? If so, which ones? If not, why not? --- ## Order of Adding Does the order in which we add values to a tree change its final shape? For each ordering of the values, add them to an initially empty BST one by one: - 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 - 6, 3, 1, 2, 4, 5, 8, 7, 9, 10 - 5, 1, 2, 3, 6, 7, 4, 8, 9, 10 Which of those trees are _better_? Why? --- ## Removing from a Tree .left-column2-small[.smaller[ Consider the tree on the right. For each of the following nodes, specify which of the three procedures should be followed to remove it from the tree (i.e., is it a leaf, a node with one child, or a node with two children?). - 87 - 80 - 45 - 60 - 90 - 35 - 25 - 70 ]] .right-column2-large[
] .below-column2[.smaller[ Show the tree after removing those nodes. If the node has two children, show both options: using the predecessor and using the successor. __In all cases start from the original tree.__ ]] --- ## Build and Search a BST Start with an empty BST and insert these values in order: .center[.big[42, 21, 64, 10, 32, 54, 75, 28, 37, 50, 59, 26]] 1. Draw the resulting tree. 2. Trace the search for 37 and for 52. List the values examined in each search. 3. Give the smallest and largest values in the tree. 4. What is the fifth-smallest value? --- ## Insertion Order and Tree Shape Insert each sequence into a separate, initially empty BST: .left-column2[ **Tree A** 40, 20, 60, 10, 30, 50, 70 **Tree B** 10, 20, 30, 40, 50, 60, 70 ] .right-column2[ **Tree C** 40, 10, 60, 20, 30, 50, 70 ] For each tree: - Draw the resulting BST and find its height (count edges on the longest root-to-leaf path). - Count the values examined when searching for 10 and for 70. - Which insertion order produces the most efficient searches in this set? Explain why. --- ## Practice Removing Nodes Build the BST by inserting these values into an empty tree: .center[.big[42, 21, 64, 10, 32, 54, 75, 28, 37, 50, 59, 26]] For each value below, classify the node as a leaf, a node with one child, or a node with two children. Then draw the tree after removing it. - Remove 10. - Remove 28. - Remove 42. Show both results: one using the inorder predecessor and one using the inorder successor. Start each removal from the original tree.