Binary Search Trees. Contents. Steven J. Zeil. July 11, Definition: Binary Search Trees The Binary Search Tree ADT...

Size: px
Start display at page:

Download "Binary Search Trees. Contents. Steven J. Zeil. July 11, Definition: Binary Search Trees The Binary Search Tree ADT..."

Transcription

1 Steven J. Zeil July 11, 2013 Contents 1 Definition: Binary Search Trees The Binary Search Tree ADT Implementing Binary Search Trees Searching a Binary Tree Inserting into Binary Search Trees Deletion Removing a Leaf Removing A Node with a Null Right Child Removing a Node with Two Non-Null Children How Fast Are Binary Search Trees? Balancing Performance Average-Case Can We Avoid the Worst Case?

2 A tree in which every parent has at most 2 children is a binary tree. The most common use of binary trees is for ADTs that require frequent searches for arbitrary keys. E.g., sets, maps For this we use a special form of binary tree, the binary search tree. 1 Definition: Binary Search Trees A binary tree T is a binary search tree if for each node n with children T L and T R : The value in n is greater than the values in every node in T L. The value in n is less than the values in every node in T R. Both T L and T R are binary search trees Question: Is this a BST? CS361 2

3 Answer: Yes, this is a binary search tree. Each node is greater than or equal to all of its left descendants, and is less than or equal than all of its right descendants The Binary Search Tree ADT Let s look at the basic interface for a binary search tree. template <typename T> class stnode ❶ public : / / stnode i s used to implement the binary search t r e e c l a s s / / making the data public s i m p l i f i e s building the c l a s s functions T nodevalue ; / / node data stnode<t> * l e f t, * right, * parent ; / / child pointers and pointer to the node s parent / / constructor stnode ( const T& item, stnode<t> * l p t r = null_ptr, CS361 3

4 stnode<t> * rptr = null_ptr, stnode<t> * pptr = null_ ptr ) : nodevalue ( item ), l e f t ( l p t r ), r i g h t ( r ptr ), parent ( pptr ) ; template <typename T> class stree ❷ public : typedef s t r e e _ i t e r a t o r <T> i t e r a t o r ; typedef stree_ const_ iterator <T> const_ iterator ; stree ( ) ; / / constructor. i n i t i a l i z e root to null_ptr and s i z e to 0 stree (T * f i r s t, T * l a s t ) ; / / constructor. i n s e r t the elements from the pointer / / range [ f i r s t, l a s t ) into the t r e e stree ( const stree <T>& tree ) ; / / copy constructor ~ stree ( ) ; / / destructor stree <T>& operator= ( const stree <T>& rhs ) ; / / assignment operator i t e r a t o r find ( const T& item ) ; ❸ / / search for item. i f found, return an i t e r a t o r pointing / / at i t in the t r e e ; otherwise, return end ( ) const_ iterator find ( const T& item ) const ; / / constant version int empty ( ) const ; CS361 4

5 / / indicate whether the t r e e i s empty int size ( ) const ; / / return the number of data items in the t r e e std : : pair < i t e r a t o r, bool> i n s e r t ( const T& item ) ; ❹ / / i f item i s not in the tree, i n s e r t i t and / / return a pair whose i t e r a t o r component points / / at item and whose bool component i s true. i f item / / i s in the tree, return a pair whose i t e r a t o r / / component points at the e x i s t i n g item and whose / / bool component i s f a l s e / / Postcondition : the t r e e s i z e increases by 1 i f item / / i s not in the t r e e int erase ( const T& item ) ; ❺ / / i f item i s in the tree, erase i t and return 1; / / otherwise, return 0 / / Postcondition : the t r e e s i z e decreases by 1 i f / / item i s in the t r e e void erase ( i t e r a t o r pos ) ; ❺ / / erase the item pointed to by pos. / / Preconditions : the t r e e i s not empty and pos points / / to an item in the t r e e. i f the t r e e i s empty, the / / function throws the underflowerror exception. i f the / / i t e r a t o r i s invalid, the function throws the referenceerror / / exception. / / Postcondition : the t r e e s i z e decreases by 1 void erase ( i t e r a t o r f i r s t, i t e r a t o r l a s t ) ; ❺ / / erase a l l items in the range [ f i r s t, l a s t ). / / Precondition : the t r e e i s not empty. i f the t r e e / / i s empty, the function throws the underflowerror / / exception. CS361 5

6 / / Postcondition : the s i z e of the t r e e decreases by / / the number of elements in the range [ f i r s t, l a s t ) i t e r a t o r begin ( ) ; / / return an i t e r a t o r pointing to the f i r s t item / / inorder const_ iterator begin ( ) const ; / / constant version i t e r a t o r end ( ) ; / / return an i t e r a t o r pointing j u s t past the end of / / the t r e e data const_ iterator end ( ) const ; / / constant version private : stnode<t> * root ; / / pointer to t r e e root int treesize ; / / number of elements in the t r e e stnode<t> *getstnode ( const T& item, stnode<t> * lptr, stnode<t> * rptr, stnode<t> * pptr ) ; / / allocate a new t r e e node and return a pointer to i t. / / i f memory allocation f a i l s, the function throws the / / memoryallocationerror exception stnode<t> * copytree ( stnode<t> * t ) ; / / recursive function used by copy constructor and assignment / / operator to assign the current t r e e as a copy of another t r e e void deletetree ( stnode<t> * t ) ; / / recursive function used by destructor and assignment / / operator to delete a l l the nodes in the t r e e CS361 6

7 stnode<t> * findnode ( const T& item ) const ; / / search for item in the t r e e. i f i t i s in the tree, / / return a pointer to i t s node ; otherwise, return null_ptr. / / used by find ( ) and erase ( ) friend c l a s s s t r e e _ i t e r a t o r <T>; friend c l a s s stree_ const_ iterator <T>; / / allow the i t e r a t o r c l a s s e s to access the private section / / of s t r e e ; This code is taken from your textbook and is the same code used in our prior discussion of tree iterators. Some points of note: ❶ The stnode template implements individual tree nodes. ❷ The stree template represents the entire tree (the whole collection of related nodes), with functions for searching, insertion, iteration, etc.. Our primary focus in this lecture will be on the find (❸), insert (❹) and erase (❺) functions. 2 Implementing Binary Search Trees Since you have, presumably, read your text s discussion of how to implement BSTs, I m mainly going to hit the high points. 2.1 Searching a Binary Tree We ll start by reviewing the basic searching algorithm. CS361 7

8 template <typename T> typename stree <T > : : i t e r a t o r stree <T > : : find ( const T& item ) stnode<t> * curr ; / / search t r e e for item curr = findnode ( item ) ; / / i f item found, return const_iterator with value current ; / / otherwise, return end ( ) i f ( curr!= null_ptr ) return i t e r a t o r ( curr, t h i s ) ; return end ( ) ; The tree s find operation works by using a private utility function, findnode, to find a pointer to the node containing the desired data and then uses that pointer to construct an iterator representing the position of that node. CS361 8

9 We search a tree by comparing the value we re searching for to the current node, t. If the value we want is smaller, we look in the left subtree. If the value we want is larger, we look in the right subtree. / / search for data item in the t r e e. i f found, return i t s node / / address ; otherwise, return null_ptr template <typename T> stnode<t>* stree <T > : : findnode ( const T& item ) const / / c y c l e t through the t r e e starting with root stnode<t> * t = root ; / / terminate on on empty subtree while ( t! = null_ ptr &&! ( item == t >nodevalue ) ) i f ( item < t >nodevalue ) t = t > l e f t ; t = t >right ; / / return pointer to node ; null_ptr i f not found return t ; You may note that this algorithm bears a certain resemblance to the binary search (17) algorithm we studied earlier in the semester. We shall see shortly that the performance of both search algorithms on a collection of N items is O(log N ), but that binary trees support faster insertion operations, allowing us to build the searchable collection in less time than when using binary search over sorted arrays. You can run this algorithm to see how it works. 2.2 Inserting into Binary Search Trees template <typename T> std::pair<typename stree<t>::iterator, bool> stree<t>::insert(const T& item) // t is current node in traversal, parent the previous node stnode<t> *t = root, *parent = null_ptr, *newnode; CS361 9

10 // terminate on on empty subtree while(t!= null_ptr) // update the parent pointer. then go left or right parent = t; // if a match occurs, return a pair whose iterator // component points at item in the tree and whose // bool component is false if (item == t->nodevalue) return std::pair<iterator, bool> (iterator(t, this), false); if (item < t->nodevalue) t = t->left; t = t->right; // create the new leaf node newnode = getstnode(item,null_ptr,null_ptr,parent); // if parent is null_ptr, insert as root node if (parent == null_ptr) root = newnode; if (item < parent->nodevalue) // insert as left child parent->left = newnode; CS361 10

11 // insert as right child parent->right = newnode; // increment size treesize++; // return an pair whose iterator component points at // the new node and whose bool component is true return std::pair<iterator, bool> (iterator(newnode, this), true); The first part of the insertion function is closely related to the recursive form of the search. In fact, we are searching for the place where the new data would reside, if it were in the tree. We know we have not found it when we reach a null pointer. Since that pointer (as either the left or right child of some parent node) was found by asking where would this data go if it were in the tree?, we know that we can, in fact, insert the data here. You might want to run this algorithm and experiment with inserting nodes into binary search trees. Take particular note of what happens if you insert data in ascending or descending order, as opposed to inserting randomly ordered data. CS361 11

12 2.3 Deletion Our tree class actually provides two distinct approaches to erasing. We can erase the data at a given position (iterator) or erase a given value, if it exists. Deleting a value is shown here. We simply do a conventional binary search tree findnode call and, if the value actually exists in the tree, erase the node at the position where we found the data. template <typename T> int stree <T > : : erase ( const T& item ) int numbererased = 1 ; / / search t r e e for item stnode<t> *p = findnode ( item ) ; / / i f item found, delete the node i f (p!= null_ptr ) erase ( i t e r a t o r (p, t h i s ) ) ; numbererased = 0 ; return numbererased ; In essence, this passes the buck to the "erase at a position" function, which we will look at next. template <typename T> void stree<t>::erase(iterator pos) // dnodeptr = pointer to node D that is deleted // pnodeptr = pointer to parent P of node D // rnodeptr = pointer to node R that replaces D stnode<t> *dnodeptr = pos.nodeptr, *pnodeptr, *rnodeptr=null_ptr; if (treesize == 0) throw underflowerror("stree erase(): tree is empty"); if (dnodeptr == null_ptr) CS361 12

13 throw referenceerror("stree erase(): invalid iterator"); // assign pnodeptr the address of P pnodeptr = dnodeptr->parent; // If D has a null_ptr pointer, the // replacement node is the other child if (dnodeptr->left == null_ptr dnodeptr->right == null_ptr) if (dnodeptr->right == null_ptr) rnodeptr = dnodeptr->left; rnodeptr = dnodeptr->right; if (rnodeptr!= null_ptr) // the parent of R is now the parent of D rnodeptr->parent = pnodeptr; // both pointers of dnodeptr are non-null_ptr. // find and unlink replacement node for D. // starting at the right child of node D, // find the node whose value is the smallest of all // nodes whose values are greater than the value in D. // unlink the node from the tree. // pofrnodeptr = pointer to parent of replacement node stnode<t> *pofrnodeptr = dnodeptr; CS361 13

14 // first possible replacement is right child of D rnodeptr = dnodeptr->right; // descend down left subtree of the right child of D, // keeping a record of current node and its parent. // when we stop, we have found the replacement while(rnodeptr->left!= null_ptr) pofrnodeptr = rnodeptr; rnodeptr = rnodeptr->left; if (pofrnodeptr == dnodeptr) // right child of deleted node is the replacement. // assign left subtree of D to left subtree of R rnodeptr->left = dnodeptr->left; // assign the parent of D as the parent of R rnodeptr->parent = pnodeptr; // assign the left child of D to have parent R dnodeptr->left->parent = rnodeptr; // we moved at least one node down a left branch // of the right child of D. unlink R from tree by // assigning its right subtree as the left child of // the parent of R pofrnodeptr->left = rnodeptr->right; // the parent of the right child of R is the CS361 14

15 // parent of R if (rnodeptr->right!= null_ptr)/**/ rnodeptr->right->parent = pofrnodeptr; // put replacement node in place of dnodeptr // assign children of R to be those of D rnodeptr->left = dnodeptr->left; rnodeptr->right = dnodeptr->right; // assign the parent of R to be the parent of D rnodeptr->parent = pnodeptr; // assign the parent pointer in the children // of R to point at R rnodeptr->left->parent = rnodeptr; rnodeptr->right->parent = rnodeptr; // complete the link to the parent node. // deleting the root node. assign new root if (pnodeptr == null_ptr) root = rnodeptr; // attach R to the correct branch of P if (dnodeptr->nodevalue < pnodeptr->nodevalue) pnodeptr->left = rnodeptr; pnodeptr->right = rnodeptr; // delete the node from memory and decrement tree size CS361 15

16 delete dnodeptr; treesize--; Here is the erase algorithm. For the moment, concentrate on the code for replacing the node we want to erase, pnodeptr, by a replacement node rnodeptr. You can see that it is careful to place the address of the replacement into either the tree root, the left child of the erased node s parent, or the right child of the erased node s parent, depending on the data value in the parent. Most of the code in this function is actually concerned with finding that replacement node. We can break down the problem of finding a suitable replacement when removing a given node from a BST into cases: 1. Removing a leaf 2. Removing a node that has only one child only a left child only a right child 3. Removing a node that has two children Removing a Leaf CS361 16

17 Case 1: Suppose we wanted to remove the 40 from this tree. What would we have to do so that the remaining nodes would still be a valid BST? Nothing at all! If we simply delete this node (setting the pointer to it from its parent to 0), what s left would still be a perfectly good binary search tree it would satisfy all the BST ordering requirements. Now, take a look at this code for removing a node, pointed at by dnodeptr, from a BST. Find the leaf case, and you can see that all we do is to delete the node. template <typename T> void stree<t>::erase(iterator pos) // dnodeptr = pointer to node D that is deleted // pnodeptr = pointer to parent P of node D // rnodeptr = pointer to node R that replaces D stnode<t> *dnodeptr = pos.nodeptr, *pnodeptr, *rnodeptr=null_ptr; if (treesize == 0) throw underflowerror("stree erase(): tree is empty"); if (dnodeptr == null_ptr) CS361 17

18 throw referenceerror("stree erase(): invalid iterator"); // assign pnodeptr the address of P pnodeptr = dnodeptr->parent; // If D has a null_ptr pointer, the // replacement node is the other child if (dnodeptr->left == null_ptr dnodeptr->right == null_ptr) if (dnodeptr->right == null_ptr) rnodeptr = dnodeptr->left; rnodeptr = dnodeptr->right; if (rnodeptr!= null_ptr) // the parent of R is now the parent of D rnodeptr->parent = pnodeptr; // both pointers of dnodeptr are non-null_ptr. // find and unlink replacement node for D. // starting at the right child of node D, // find the node whose value is the smallest of all // nodes whose values are greater than the value in D. // unlink the node from the tree. // pofrnodeptr = pointer to parent of replacement node stnode<t> *pofrnodeptr = dnodeptr; CS361 18

19 // first possible replacement is right child of D rnodeptr = dnodeptr->right; // descend down left subtree of the right child of D, // keeping a record of current node and its parent. // when we stop, we have found the replacement while(rnodeptr->left!= null_ptr) pofrnodeptr = rnodeptr; rnodeptr = rnodeptr->left; if (pofrnodeptr == dnodeptr) // right child of deleted node is the replacement. // assign left subtree of D to left subtree of R rnodeptr->left = dnodeptr->left; // assign the parent of D as the parent of R rnodeptr->parent = pnodeptr; // assign the left child of D to have parent R dnodeptr->left->parent = rnodeptr; // we moved at least one node down a left branch // of the right child of D. unlink R from tree by // assigning its right subtree as the left child of // the parent of R pofrnodeptr->left = rnodeptr->right; CS361 19

20 // the parent of the right child of R is the // parent of R if (rnodeptr->right!= null_ptr)/**/ rnodeptr->right->parent = pofrnodeptr; // put replacement node in place of dnodeptr // assign children of R to be those of D rnodeptr->left = dnodeptr->left; rnodeptr->right = dnodeptr->right; // assign the parent of R to be the parent of D rnodeptr->parent = pnodeptr; // assign the parent pointer in the children // of R to point at R rnodeptr->left->parent = rnodeptr; rnodeptr->right->parent = rnodeptr; // complete the link to the parent node. // deleting the root node. assign new root if (pnodeptr == null_ptr) root = rnodeptr; // attach R to the correct branch of P if (dnodeptr->nodevalue < pnodeptr->nodevalue) pnodeptr->left = rnodeptr; pnodeptr->right = rnodeptr; // delete the node from memory and decrement tree size delete dnodeptr; CS361 20

21 treesize--; (Note that when we assign dnodeptr->left to rnodeptr, that in this leaf case dnodeptr->left is null.) So if we are removing a tree leaf, we "replace" it by a null pointer Removing A Node with a Null Right Child Case 2: Suppose we wanted to remove the 20 or the 70 from this tree. What would we have to do so that the remaining nodes would still be a valid BST? There is one pointer to the node being deleted, and one pointer from that node to its only child. So this is actually a bit like deleting a node from the middle of a linked list. All we need to do is to reroute the pointer from the parent ( 30 ) to the node we want to remove, making that pointer point directly to the child of the node we are going to remove. CS361 21

22 For example, starting from this: Verify for yourself if we remove 20: CS361 22

23 or 70: in this manner, that the results are still valid BSTs. template <typename T> void stree<t>::erase(iterator pos) // dnodeptr = pointer to node D that is deleted // pnodeptr = pointer to parent P of node D // rnodeptr = pointer to node R that replaces D stnode<t> *dnodeptr = pos.nodeptr, *pnodeptr, *rnodeptr=null_ptr; if (treesize == 0) throw underflowerror("stree erase(): tree is empty"); if (dnodeptr == null_ptr) throw referenceerror("stree erase(): invalid iterator"); // assign pnodeptr the address of P CS361 23

24 pnodeptr = dnodeptr->parent; // If D has a null_ptr pointer, the // replacement node is the other child if (dnodeptr->left == null_ptr dnodeptr->right == null_ptr) if (dnodeptr->right == null_ptr) rnodeptr = dnodeptr->left; rnodeptr = dnodeptr->right; if (rnodeptr!= null_ptr) // the parent of R is now the parent of D rnodeptr->parent = pnodeptr; // both pointers of dnodeptr are non-null_ptr. // find and unlink replacement node for D. // starting at the right child of node D, // find the node whose value is the smallest of all // nodes whose values are greater than the value in D. // unlink the node from the tree. // pofrnodeptr = pointer to parent of replacement node stnode<t> *pofrnodeptr = dnodeptr; // first possible replacement is right child of D rnodeptr = dnodeptr->right; CS361 24

25 // descend down left subtree of the right child of D, // keeping a record of current node and its parent. // when we stop, we have found the replacement while(rnodeptr->left!= null_ptr) pofrnodeptr = rnodeptr; rnodeptr = rnodeptr->left; if (pofrnodeptr == dnodeptr) // right child of deleted node is the replacement. // assign left subtree of D to left subtree of R rnodeptr->left = dnodeptr->left; // assign the parent of D as the parent of R rnodeptr->parent = pnodeptr; // assign the left child of D to have parent R dnodeptr->left->parent = rnodeptr; // we moved at least one node down a left branch // of the right child of D. unlink R from tree by // assigning its right subtree as the left child of // the parent of R pofrnodeptr->left = rnodeptr->right; // the parent of the right child of R is the // parent of R if (rnodeptr->right!= null_ptr)/**/ rnodeptr->right->parent = pofrnodeptr; CS361 25

26 // put replacement node in place of dnodeptr // assign children of R to be those of D rnodeptr->left = dnodeptr->left; rnodeptr->right = dnodeptr->right; // assign the parent of R to be the parent of D rnodeptr->parent = pnodeptr; // assign the parent pointer in the children // of R to point at R rnodeptr->left->parent = rnodeptr; rnodeptr->right->parent = rnodeptr; // complete the link to the parent node. // deleting the root node. assign new root if (pnodeptr == null_ptr) root = rnodeptr; // attach R to the correct branch of P if (dnodeptr->nodevalue < pnodeptr->nodevalue) pnodeptr->left = rnodeptr; pnodeptr->right = rnodeptr; // delete the node from memory and decrement tree size delete dnodeptr; treesize--; Again, take a look at this code for the case when the node being erased has exactly one child. Notice that its non-null child CS361 26

27 is chosen as the replacement node, rnodeptr Removing a Node with Two Non-Null Children Case 3: Suppose we wanted to remove the 50 or the 30 from this tree. What would we have to do so that the remaining nodes would still be a valid BST? This is a hard case. Clearly, if we remove either the "50" or "30" nodes, we break the tree into pieces, with no obvious place to put the now-detached subtrees. So let s take a different tack. Instead of deleting this node, is there some other data value that we could put into that node that would preserve the BST ordering (all nodes to the left must be less, all nodes to the right must be greater or equal)? There are, in fact, two values that we could safely put in there: the smallest value from the right subtree, or the largest value from the left subtree. We can find the largest value on the left by taking one step to the left then running as far down to the right as we can go We can find the smallest value on the right by taking one step to the right then running as far down to the left as we can go CS361 27

28 Now, if we replace 30 by the largest value from the left: CS361 28

29 or by the smallest value from the right, the results are properly ordered for a BST, except possibly for the node we just copied the value from. But since that node is now redundant, we can delete it from the tree. And here s the best part. Since we find the node to copy from by running as far as we can go in one direction or the other, we know that the node we copied from has at least 1 null child pointer (otherwise we would have kept running past it). So removing it from the tree will always fall into one of the earlier, simpler cases (leaf or only one child). template <typename T> void stree<t>::erase(iterator pos) // dnodeptr = pointer to node D that is deleted // pnodeptr = pointer to parent P of node D // rnodeptr = pointer to node R that replaces D stnode<t> *dnodeptr = pos.nodeptr, *pnodeptr, *rnodeptr=null_ptr; if (treesize == 0) throw underflowerror("stree erase(): tree is empty"); if (dnodeptr == null_ptr) CS361 29

30 throw referenceerror("stree erase(): invalid iterator"); // assign pnodeptr the address of P pnodeptr = dnodeptr->parent; // If D has a null_ptr pointer, the // replacement node is the other child if (dnodeptr->left == null_ptr dnodeptr->right == null_ptr) if (dnodeptr->right == null_ptr) rnodeptr = dnodeptr->left; rnodeptr = dnodeptr->right; if (rnodeptr!= null_ptr) // the parent of R is now the parent of D rnodeptr->parent = pnodeptr; // both pointers of dnodeptr are non-null_ptr. // find and unlink replacement node for D. // starting at the right child of node D, // find the node whose value is the smallest of all // nodes whose values are greater than the value in D. // unlink the node from the tree. // pofrnodeptr = pointer to parent of replacement node CS361 30

31 stnode<t> *pofrnodeptr = dnodeptr; // first possible replacement is right child of D rnodeptr = dnodeptr->right; // descend down left subtree of the right child of D, // keeping a record of current node and its parent. // when we stop, we have found the replacement while(rnodeptr->left!= null_ptr) pofrnodeptr = rnodeptr; rnodeptr = rnodeptr->left; if (pofrnodeptr == dnodeptr) // right child of deleted node is the replacement. // assign left subtree of D to left subtree of R rnodeptr->left = dnodeptr->left; // assign the parent of D as the parent of R rnodeptr->parent = pnodeptr; // assign the left child of D to have parent R dnodeptr->left->parent = rnodeptr; CS361 31

32 // we moved at least one node down a left branch // of the right child of D. unlink R from tree by // assigning its right subtree as the left child of // the parent of R pofrnodeptr->left = rnodeptr->right; // the parent of the right child of R is the // parent of R if (rnodeptr->right!= null_ptr)/**/ rnodeptr->right->parent = pofrnodeptr; // put replacement node in place of dnodeptr // assign children of R to be those of D rnodeptr->left = dnodeptr->left; rnodeptr->right = dnodeptr->right; // assign the parent of R to be the parent of D rnodeptr->parent = pnodeptr; // assign the parent pointer in the children // of R to point at R rnodeptr->left->parent = rnodeptr; rnodeptr->right->parent = rnodeptr; // complete the link to the parent node. CS361 32

33 // deleting the root node. assign new root if (pnodeptr == null_ptr) root = rnodeptr; // attach R to the correct branch of P if (dnodeptr->nodevalue < pnodeptr->nodevalue) pnodeptr->left = rnodeptr; pnodeptr->right = rnodeptr; // delete the node from memory and decrement tree size delete dnodeptr; treesize--; Again, take a look at the code for removing a node. This code does the "step to the right, then run to the left" behavior we have just described in order to find the replacement node. The remaining code is concerned with removing that replacement node from where it currently resides so that we can then link it in to the parent of the node being erased. Finally, try running this algorithm, available as erase from a position. Try to observe each of the major cases, as outlined here, in action. 3 How Fast Are Binary Search Trees? Each step in the BST insert and findnode algorithms move one level deeper in the tree. Similarly, in erase, the only part that is not constant time is the running down the tree to find the smallest value to the right. The number of recursive calls/loop iterations in all these algorithms is therefore no greater than the height of the tree. But how high can a BST be? That depends on how well the tree is balanced. CS361 33

34 3.1 Balancing A binary tree is balanced if for every interior node, the height of its two children differ by at most Unbalanced trees are easy to obtain. This is a BST CS361 34

35 But, so is this! The shape of the tree depends upon the order of insertions. The worst case is when the data being inserted is already in order (or in reverse order). In that case, the tree degenerates into a sorted linked list, as shown above. The best case is when the tree is balanced, meaning that, for each node, the heights of the node s children are nearly the same. CS361 35

36 3.2 Performance / / search for data item in the t r e e. i f found, return i t s node / / address ; otherwise, return null_ptr template <typename T> stnode<t>* stree <T > : : findnode ( const T& item ) const / / c y c l e t through the t r e e starting with root stnode<t> * t = root ; / / terminate on on empty subtree while ( t! = null_ ptr &&! ( item == t >nodevalue ) ) i f ( item < t >nodevalue ) t = t > l e f t ; t = t >right ; Consider the findnode operation on a nearly balanced tree with N nodes. Question: What is the complexity of the best case? O(1) O(log N ) O(N ) O(N log N ) / / return pointer to node ; null_ptr i f not found return t ; O(N 2) CS361 36

37 Answer: In the best case, we find what we re looking for in the root of the tree. That s O(1) time / / search for data item in the t r e e. i f found, return i t s node / / address ; otherwise, return null_ptr template <typename T> stnode<t>* stree <T > : : findnode ( const T& item ) const / / c y c l e t through the t r e e starting with root stnode<t> * t = root ; / / terminate on on empty subtree while ( t! = null_ ptr &&! ( item == t >nodevalue ) ) i f ( item < t >nodevalue ) t = t > l e f t ; t = t >right ; / / return pointer to node ; null_ptr i f not found return t ; Question: Consider the findnode operation on a nearly balanced tree with N nodes. What is the complexity of the worst case? O(1) O(log N ) O(N ) O(N log N ) O(N 2) CS361 37

38 Answer: The findnode operation starts at the root and moves down one level each recursion. So it is, in the worst case, O(h) where h is the height of the tree But how high is a balanced tree? A nearly balanced tree will be height log N. Consider a tree that is completely balanced and has its lowest level full. Since every node on the lowest level shares a parent with one other, there will be exactly half as many nodes on the next-to-lowest level as on the lowest. And, by the same reasoning, each level will have half as many nodes as the one below it, until we finally get to the single root at the top of the tree. So a balanced tree has height log N, and searching a balanced binary tree would be O(log N ). / / search for data item in the t r e e. i f found, return i t s node / / address ; otherwise, return null_ptr template <typename T> stnode<t>* stree <T > : : findnode ( const T& item ) const / / c y c l e t through the t r e e starting with root stnode<t> * t = root ; / / terminate on on empty subtree while ( t! = null_ ptr &&! ( item == t >nodevalue ) ) i f ( item < t >nodevalue ) t = t > l e f t ; t = t >right ; / / return pointer to node ; null_ptr i f not found return t ; Question: Consider the findnode operation on a degenerate tree with N nodes. What is the complexity of the worst case? O(1) O(log N ) O(N ) O(N log N ) O(N 2) CS361 38

39 Answer: A degenerate tree looks like a linked list. In the worst case, the value we re looking for is at the end of the list, so we have to search through all N nodes to get there. Thus the worst case is O(N ) There s quite a difference, then, between the worst case behavior of trees, depending upon the tree s shape. 3.3 Average-Case So the question is, does the "average" binary tree look more like the balanced or the degenerate case? An intuitive argument is: No tree with n nodes has height < log(n) No tree with n nodes has height > n Average depth of all nodes is therefore bounded between n/2 and (logn)/2. The more unbalanced a tree is, the less likely that a random insertion would increase the tree height. CS361 39

40 For example, if we are inserting into this tree, then any insertion will increase the tree s height But if we were inserting a randomly selected value into this one, then there is only a 2/8 chance that we will increase the height of the tree CS361 40

41 For trees that are somewhere between those two extremes, the chances of a random insertion actually increasing the height of the tree will fall somewhere between those two probability extremes. Insertions that don t increase the tree height make the tree more balanced. So, the more unbalanced a tree is, the more likely that a random insertion will actually tend to increase the balance of the tree. This suggests (but does not prove) that randomly constructed binary search trees tend to be reasonably balanced. It is possible to prove this claim, but the proof is beyond the scope of this class. But, it s not safe to be too sanguine about the height of binary search trees. Although random construction tends to yield reasonable balance, in real applications we often do not get random values. Question: Which of the following data would, if inserted into an initially empty binary search tree, yield a degenerate tree? data that is in ascending order data that is in descending order both of the above none of the above 3.4 Can We Avoid the Worst Case? Both data in ascending and descending order results in degenerate trees. (Try it if you are not convinced.) CS361 41

42 It s very common to get data that is in sorted or almost sorted order, so degenerate behavior turns out to be more common than we might expect. Also, the arguments made so far don t take deletions into account, which tend to unbalance trees. Later, we ll look at variants of the binary search tree that use more elaborate insertion and deletion algorithms to maintain tree balance. CS361 42

the pointer range [first, last) into the tree

the pointer range [first, last) into the tree 1 #ifndef BINARY_SEARCH_TREE_CLASS 2 #define BINARY_SEARCH_TREE_CLASS 3 4 #ifndef NULL 5 #include 6 #endif // NULL 7 8 #include // for setw() 9 #include // for format conversion

More information

Advanced Data Structures and Algorithms

Advanced Data Structures and Algorithms Advanced Data Structures and Algorithms CS 361 - Fall 2013 Lec. #07: Trees & Binary Search Trees Tamer Nadeem Dept. of Computer Science Class Objective/Overview Familiarize with Trees and Related Terminologies

More information

Traversing Trees with Iterators

Traversing Trees with Iterators Steven J. Zeil June 25, 2013 Contents 1 Iterating over Trees 4 1.1 begin()..................................... 6 1.2 operator++................................... 7 2 Iterators using Parent Pointers 11

More information

Traversing Trees with Iterators

Traversing Trees with Iterators Steven J. Zeil June 25, 2013 Contents 1 Iterating over Trees 3 1.1 begin()................................................................ 5 1.2 operator++..............................................................

More information

Tutorial AVL TREES. arra[5] = {1,2,3,4,5} arrb[8] = {20,30,80,40,10,60,50,70} FIGURE 1 Equivalent Binary Search and AVL Trees. arra = {1, 2, 3, 4, 5}

Tutorial AVL TREES. arra[5] = {1,2,3,4,5} arrb[8] = {20,30,80,40,10,60,50,70} FIGURE 1 Equivalent Binary Search and AVL Trees. arra = {1, 2, 3, 4, 5} 1 Tutorial AVL TREES Binary search trees are designed for efficient access to data. In some cases, however, a binary search tree is degenerate or "almost degenerate" with most of the n elements descending

More information

void insert( Type const & ) void push_front( Type const & )

void insert( Type const & ) void push_front( Type const & ) 6.1 Binary Search Trees A binary search tree is a data structure that can be used for storing sorted data. We will begin by discussing an Abstract Sorted List or Sorted List ADT and then proceed to describe

More information

Binary Trees and Binary Search Trees

Binary Trees and Binary Search Trees Binary Trees and Binary Search Trees Learning Goals After this unit, you should be able to... Determine if a given tree is an instance of a particular type (e.g. binary, and later heap, etc.) Describe

More information

Tree traversals and binary trees

Tree traversals and binary trees Tree traversals and binary trees Comp Sci 1575 Data Structures Valgrind Execute valgrind followed by any flags you might want, and then your typical way to launch at the command line in Linux. Assuming

More information

Algorithms. AVL Tree

Algorithms. AVL Tree Algorithms AVL Tree Balanced binary tree The disadvantage of a binary search tree is that its height can be as large as N-1 This means that the time needed to perform insertion and deletion and many other

More information

Binary Trees. BSTs. For example: Jargon: Data Structures & Algorithms. root node. level: internal node. edge.

Binary Trees. BSTs. For example: Jargon: Data Structures & Algorithms. root node. level: internal node. edge. Binary Trees 1 A binary tree is either empty, or it consists of a node called the root together with two binary trees called the left subtree and the right subtree of the root, which are disjoint from

More information

Trees. Chapter 6. strings. 3 Both position and Enumerator are similar in concept to C++ iterators, although the details are quite different.

Trees. Chapter 6. strings. 3 Both position and Enumerator are similar in concept to C++ iterators, although the details are quite different. Chapter 6 Trees In a hash table, the items are not stored in any particular order in the table. This is fine for implementing Sets and Maps, since for those abstract data types, the only thing that matters

More information

Binary Trees, Binary Search Trees

Binary Trees, Binary Search Trees Binary Trees, Binary Search Trees Trees Linear access time of linked lists is prohibitive Does there exist any simple data structure for which the running time of most operations (search, insert, delete)

More information

Module 4: Index Structures Lecture 13: Index structure. The Lecture Contains: Index structure. Binary search tree (BST) B-tree. B+-tree.

Module 4: Index Structures Lecture 13: Index structure. The Lecture Contains: Index structure. Binary search tree (BST) B-tree. B+-tree. The Lecture Contains: Index structure Binary search tree (BST) B-tree B+-tree Order file:///c /Documents%20and%20Settings/iitkrana1/My%20Documents/Google%20Talk%20Received%20Files/ist_data/lecture13/13_1.htm[6/14/2012

More information

Title Description Participants Textbook

Title Description Participants Textbook Podcast Ch18d Title: Binary Search Tree Iterator Description: Additional operations first and last; the BST iterator Participants: Barry Kurtz (instructor); John Helfert and Tobie Williams (students) Textbook:

More information

Trees. (Trees) Data Structures and Programming Spring / 28

Trees. (Trees) Data Structures and Programming Spring / 28 Trees (Trees) Data Structures and Programming Spring 2018 1 / 28 Trees A tree is a collection of nodes, which can be empty (recursive definition) If not empty, a tree consists of a distinguished node r

More information

Chapter 20: Binary Trees

Chapter 20: Binary Trees Chapter 20: Binary Trees 20.1 Definition and Application of Binary Trees Definition and Application of Binary Trees Binary tree: a nonlinear linked list in which each node may point to 0, 1, or two other

More information

CSCI-1200 Data Structures Fall 2017 Lecture 17 Trees, Part I

CSCI-1200 Data Structures Fall 2017 Lecture 17 Trees, Part I Review from Lecture 16 CSCI-1200 Data Structures Fall 2017 Lecture 17 Trees, Part I Maps containing more complicated values. Example: index mapping words to the text line numbers on which they appear.

More information

Trees, Part 1: Unbalanced Trees

Trees, Part 1: Unbalanced Trees Trees, Part 1: Unbalanced Trees The first part of this chapter takes a look at trees in general and unbalanced binary trees. The second part looks at various schemes to balance trees and/or make them more

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 11: Binary Search Trees MOUNA KACEM mouna@cs.wisc.edu Fall 2018 General Overview of Data Structures 2 Introduction to trees 3 Tree: Important non-linear data structure

More information

CSCI2100B Data Structures Trees

CSCI2100B Data Structures Trees CSCI2100B Data Structures Trees Irwin King king@cse.cuhk.edu.hk http://www.cse.cuhk.edu.hk/~king Department of Computer Science & Engineering The Chinese University of Hong Kong Introduction General Tree

More information

Operations on Heap Tree The major operations required to be performed on a heap tree are Insertion, Deletion, and Merging.

Operations on Heap Tree The major operations required to be performed on a heap tree are Insertion, Deletion, and Merging. Priority Queue, Heap and Heap Sort In this time, we will study Priority queue, heap and heap sort. Heap is a data structure, which permits one to insert elements into a set and also to find the largest

More information

8. Binary Search Tree

8. Binary Search Tree 8 Binary Search Tree Searching Basic Search Sequential Search : Unordered Lists Binary Search : Ordered Lists Tree Search Binary Search Tree Balanced Search Trees (Skipped) Sequential Search int Seq-Search

More information

CS102 Binary Search Trees

CS102 Binary Search Trees CS102 Binary Search Trees Prof Tejada 1 To speed up insertion, removal and search, modify the idea of a Binary Tree to create a Binary Search Tree (BST) Binary Search Trees Binary Search Trees have one

More information

SCJ2013 Data Structure & Algorithms. Binary Search Tree. Nor Bahiah Hj Ahmad

SCJ2013 Data Structure & Algorithms. Binary Search Tree. Nor Bahiah Hj Ahmad SCJ2013 Data Structure & Algorithms Binary Search Tree Nor Bahiah Hj Ahmad Binary Search Tree A binary search tree has the following properties: For every node n in the tree Value of n is greater than

More information

! Tree: set of nodes and directed edges. ! Parent: source node of directed edge. ! Child: terminal node of directed edge

! Tree: set of nodes and directed edges. ! Parent: source node of directed edge. ! Child: terminal node of directed edge Trees & Heaps Week 12 Gaddis: 20 Weiss: 21.1-3 CS 5301 Fall 2018 Jill Seaman!1 Tree: non-recursive definition! Tree: set of nodes and directed edges - root: one node is distinguished as the root - Every

More information

Data Structures and Algorithms

Data Structures and Algorithms Data Structures and Algorithms CS245-2017S-06 Binary Search Trees David Galles Department of Computer Science University of San Francisco 06-0: Ordered List ADT Operations: Insert an element in the list

More information

9/29/2016. Chapter 4 Trees. Introduction. Terminology. Terminology. Terminology. Terminology

9/29/2016. Chapter 4 Trees. Introduction. Terminology. Terminology. Terminology. Terminology Introduction Chapter 4 Trees for large input, even linear access time may be prohibitive we need data structures that exhibit average running times closer to O(log N) binary search tree 2 Terminology recursive

More information

Advanced Java Concepts Unit 5: Trees. Notes and Exercises

Advanced Java Concepts Unit 5: Trees. Notes and Exercises Advanced Java Concepts Unit 5: Trees. Notes and Exercises A Tree is a data structure like the figure shown below. We don t usually care about unordered trees but that s where we ll start. Later we will

More information

CSE100. Advanced Data Structures. Lecture 13. (Based on Paul Kube course materials)

CSE100. Advanced Data Structures. Lecture 13. (Based on Paul Kube course materials) CSE100 Advanced Data Structures Lecture 13 (Based on Paul Kube course materials) CSE 100 Priority Queues in Huffman s algorithm Heaps and Priority Queues Time and space costs of coding with Huffman codes

More information

Binary Search Tree. Revised based on textbook author s notes.

Binary Search Tree. Revised based on textbook author s notes. Binary Search Tree Revised based on textbook author s notes. Search Trees The tree structure can be used for searching. Each node contains a search key as part of its data or payload. Nodes are organized

More information

Trees 2: Linked Representation, Tree Traversal, and Binary Search Trees

Trees 2: Linked Representation, Tree Traversal, and Binary Search Trees Trees 2: Linked Representation, Tree Traversal, and Binary Search Trees Linked representation of binary tree Again, as with linked list, entire tree can be represented with a single pointer -- in this

More information

Trees 2: Linked Representation, Tree Traversal, and Binary Search Trees

Trees 2: Linked Representation, Tree Traversal, and Binary Search Trees Trees 2: Linked Representation, Tree Traversal, and Binary Search Trees Linked representation of binary tree Again, as with linked list, entire tree can be represented with a single pointer -- in this

More information

INF2220: algorithms and data structures Series 1

INF2220: algorithms and data structures Series 1 Universitetet i Oslo Institutt for Informatikk A. Maus, R.K. Runde, I. Yu INF2220: algorithms and data structures Series 1 Topic Trees & estimation of running time (Exercises with hints for solution) Issued:

More information

CS302 - Data Structures using C++

CS302 - Data Structures using C++ CS302 - Data Structures using C++ Topic: Implementation Kostas Alexis s Definition: A (BST) is a binary tree where each node has a Comparable key (and an associated value) and satisfies the restriction

More information

Data Structures and Algorithms

Data Structures and Algorithms Data Structures and Algorithms CS245-2008S-19 B-Trees David Galles Department of Computer Science University of San Francisco 19-0: Indexing Operations: Add an element Remove an element Find an element,

More information

Lecture 15 Binary Search Trees

Lecture 15 Binary Search Trees Lecture 15 Binary Search Trees 15-122: Principles of Imperative Computation (Fall 2017) Frank Pfenning, André Platzer, Rob Simmons, Iliano Cervesato In this lecture, we will continue considering ways to

More information

4. Trees. 4.1 Preliminaries. 4.2 Binary trees. 4.3 Binary search trees. 4.4 AVL trees. 4.5 Splay trees. 4.6 B-trees. 4. Trees

4. Trees. 4.1 Preliminaries. 4.2 Binary trees. 4.3 Binary search trees. 4.4 AVL trees. 4.5 Splay trees. 4.6 B-trees. 4. Trees 4. Trees 4.1 Preliminaries 4.2 Binary trees 4.3 Binary search trees 4.4 AVL trees 4.5 Splay trees 4.6 B-trees Malek Mouhoub, CS340 Fall 2002 1 4.1 Preliminaries A Root B C D E F G Height=3 Leaves H I J

More information

CSCI-1200 Data Structures Fall 2018 Lecture 19 Trees, Part III

CSCI-1200 Data Structures Fall 2018 Lecture 19 Trees, Part III CSCI-1200 Data Structures Fall 2018 Lecture 19 Trees, Part III Review from Lecture 17 & 18 Overview of the ds set implementation begin, find, destroy_tree, insert In-order, pre-order, and post-order traversal;

More information

Largest Online Community of VU Students

Largest Online Community of VU Students WWW.VUPages.com http://forum.vupages.com WWW.VUTUBE.EDU.PK Largest Online Community of VU Students MIDTERM EXAMINATION SEMESTER FALL 2003 CS301-DATA STRUCTURE Total Marks:86 Duration: 60min Instructions

More information

Fall, 2015 Prof. Jungkeun Park

Fall, 2015 Prof. Jungkeun Park Data Structures and Algorithms Binary Search Trees Fall, 2015 Prof. Jungkeun Park Copyright Notice: This material is modified version of the lecture slides by Prof. Rada Mihalcea in Univ. of North Texas.

More information

Lecture 23: Binary Search Trees

Lecture 23: Binary Search Trees Lecture 23: Binary Search Trees CS 62 Fall 2017 Kim Bruce & Alexandra Papoutsaki 1 BST A binary tree is a binary search tree iff it is empty or if the value of every node is both greater than or equal

More information

CSCI-1200 Data Structures Spring 2018 Lecture 16 Trees, Part I

CSCI-1200 Data Structures Spring 2018 Lecture 16 Trees, Part I CSCI-1200 Data Structures Spring 2018 Lecture 16 Trees, Part I Review from Lecture 15 Maps containing more complicated values. Example: index mapping words to the text line numbers on which they appear.

More information

Uses for Trees About Trees Binary Trees. Trees. Seth Long. January 31, 2010

Uses for Trees About Trees Binary Trees. Trees. Seth Long. January 31, 2010 Uses for About Binary January 31, 2010 Uses for About Binary Uses for Uses for About Basic Idea Implementing Binary Example: Expression Binary Search Uses for Uses for About Binary Uses for Storage Binary

More information

BINARY SEARCH TREES cs2420 Introduction to Algorithms and Data Structures Spring 2015

BINARY SEARCH TREES cs2420 Introduction to Algorithms and Data Structures Spring 2015 BINARY SEARCH TREES cs2420 Introduction to Algorithms and Data Structures Spring 2015 1 administrivia 2 -assignment 7 due tonight at midnight -asking for regrades through assignment 5 and midterm must

More information

Data Structures in Java

Data Structures in Java Data Structures in Java Lecture 9: Binary Search Trees. 10/7/015 Daniel Bauer 1 Contents 1. Binary Search Trees. Implementing Maps with BSTs Map ADT A map is collection of (key, value) pairs. Keys are

More information

Lecture Notes on Binary Search Trees

Lecture Notes on Binary Search Trees Lecture Notes on Binary Search Trees 15-122: Principles of Imperative Computation Frank Pfenning André Platzer Lecture 15 March 6, 2014 1 Introduction In this lecture, we will continue considering associative

More information

- 1 - Handout #22S May 24, 2013 Practice Second Midterm Exam Solutions. CS106B Spring 2013

- 1 - Handout #22S May 24, 2013 Practice Second Midterm Exam Solutions. CS106B Spring 2013 CS106B Spring 2013 Handout #22S May 24, 2013 Practice Second Midterm Exam Solutions Based on handouts by Eric Roberts and Jerry Cain Problem One: Reversing a Queue One way to reverse the queue is to keep

More information

CSCI-1200 Data Structures Spring 2015 Lecture 18 Trees, Part I

CSCI-1200 Data Structures Spring 2015 Lecture 18 Trees, Part I CSCI-1200 Data Structures Spring 2015 Lecture 18 Trees, Part I Review from Lectures 17 Maps containing more complicated values. Example: index mapping words to the text line numbers on which they appear.

More information

CSCI-1200 Data Structures Spring 2015 Lecture 20 Trees, Part III

CSCI-1200 Data Structures Spring 2015 Lecture 20 Trees, Part III CSCI-1200 Data Structures Spring 2015 Lecture 20 Trees, Part III Review from Lecture 18 & 19 Overview of the ds set implementation begin, find, destroy_tree, insert In-order, pre-order, and post-order

More information

CSC212 Data Structure - Section FG

CSC212 Data Structure - Section FG CSC212 Data Structure - Section FG Lecture 17 B-Trees and the Set Class Instructor: Feng HU Department of Computer Science City College of New York @ Feng HU, 2016 1 Topics Why B-Tree The problem of an

More information

Priority Queues. 1 Introduction. 2 Naïve Implementations. CSci 335 Software Design and Analysis III Chapter 6 Priority Queues. Prof.

Priority Queues. 1 Introduction. 2 Naïve Implementations. CSci 335 Software Design and Analysis III Chapter 6 Priority Queues. Prof. Priority Queues 1 Introduction Many applications require a special type of queuing in which items are pushed onto the queue by order of arrival, but removed from the queue based on some other priority

More information

Lecture Notes on Binary Search Trees

Lecture Notes on Binary Search Trees Lecture Notes on Binary Search Trees 15-122: Principles of Imperative Computation Frank Pfenning André Platzer Lecture 16 March 17, 2015 1 Introduction In this lecture, we will continue considering ways

More information

Discussion 2C Notes (Week 8, February 25) TA: Brian Choi Section Webpage:

Discussion 2C Notes (Week 8, February 25) TA: Brian Choi Section Webpage: Discussion 2C Notes (Week 8, February 25) TA: Brian Choi (schoi@cs.ucla.edu) Section Webpage: http://www.cs.ucla.edu/~schoi/cs32 Trees Definitions Yet another data structure -- trees. Just like a linked

More information

CSCI Trees. Mark Redekopp David Kempe

CSCI Trees. Mark Redekopp David Kempe CSCI 104 2-3 Trees Mark Redekopp David Kempe Trees & Maps/Sets C++ STL "maps" and "sets" use binary search trees internally to store their keys (and values) that can grow or contract as needed This allows

More information

Search Trees. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Binary Search Trees

Search Trees. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Binary Search Trees Unit 9, Part 2 Search Trees Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Binary Search Trees Search-tree property: for each node k: all nodes in k s left subtree are < k all nodes

More information

Balanced Binary Search Trees. Victor Gao

Balanced Binary Search Trees. Victor Gao Balanced Binary Search Trees Victor Gao OUTLINE Binary Heap Revisited BST Revisited Balanced Binary Search Trees Rotation Treap Splay Tree BINARY HEAP: REVIEW A binary heap is a complete binary tree such

More information

An AVL tree with N nodes is an excellent data. The Big-Oh analysis shows that most operations finish within O(log N) time

An AVL tree with N nodes is an excellent data. The Big-Oh analysis shows that most operations finish within O(log N) time B + -TREES MOTIVATION An AVL tree with N nodes is an excellent data structure for searching, indexing, etc. The Big-Oh analysis shows that most operations finish within O(log N) time The theoretical conclusion

More information

Treaps. 1 Binary Search Trees (BSTs) CSE341T/CSE549T 11/05/2014. Lecture 19

Treaps. 1 Binary Search Trees (BSTs) CSE341T/CSE549T 11/05/2014. Lecture 19 CSE34T/CSE549T /05/04 Lecture 9 Treaps Binary Search Trees (BSTs) Search trees are tree-based data structures that can be used to store and search for items that satisfy a total order. There are many types

More information

Lecture 15 Notes Binary Search Trees

Lecture 15 Notes Binary Search Trees Lecture 15 Notes Binary Search Trees 15-122: Principles of Imperative Computation (Spring 2016) Frank Pfenning, André Platzer, Rob Simmons 1 Introduction In this lecture, we will continue considering ways

More information

! Tree: set of nodes and directed edges. ! Parent: source node of directed edge. ! Child: terminal node of directed edge

! Tree: set of nodes and directed edges. ! Parent: source node of directed edge. ! Child: terminal node of directed edge Trees (& Heaps) Week 12 Gaddis: 20 Weiss: 21.1-3 CS 5301 Spring 2015 Jill Seaman 1 Tree: non-recursive definition! Tree: set of nodes and directed edges - root: one node is distinguished as the root -

More information

Parallel and Sequential Data Structures and Algorithms Lecture (Spring 2012) Lecture 16 Treaps; Augmented BSTs

Parallel and Sequential Data Structures and Algorithms Lecture (Spring 2012) Lecture 16 Treaps; Augmented BSTs Lecture 16 Treaps; Augmented BSTs Parallel and Sequential Data Structures and Algorithms, 15-210 (Spring 2012) Lectured by Margaret Reid-Miller 8 March 2012 Today: - More on Treaps - Ordered Sets and Tables

More information

Binary Trees and Huffman Encoding Binary Search Trees

Binary Trees and Huffman Encoding Binary Search Trees Binary Trees and Huffman Encoding Binary Search Trees Computer Science E-22 Harvard Extension School David G. Sullivan, Ph.D. Motivation: Maintaining a Sorted Collection of Data A data dictionary is a

More information

Introduction. for large input, even access time may be prohibitive we need data structures that exhibit times closer to O(log N) binary search tree

Introduction. for large input, even access time may be prohibitive we need data structures that exhibit times closer to O(log N) binary search tree Chapter 4 Trees 2 Introduction for large input, even access time may be prohibitive we need data structures that exhibit running times closer to O(log N) binary search tree 3 Terminology recursive definition

More information

Trees, Binary Trees, and Binary Search Trees

Trees, Binary Trees, and Binary Search Trees COMP171 Trees, Binary Trees, and Binary Search Trees 2 Trees Linear access time of linked lists is prohibitive Does there exist any simple data structure for which the running time of most operations (search,

More information

Advanced Set Representation Methods

Advanced Set Representation Methods Advanced Set Representation Methods AVL trees. 2-3(-4) Trees. Union-Find Set ADT DSA - lecture 4 - T.U.Cluj-Napoca - M. Joldos 1 Advanced Set Representation. AVL Trees Problem with BSTs: worst case operation

More information

Trees. Eric McCreath

Trees. Eric McCreath Trees Eric McCreath 2 Overview In this lecture we will explore: general trees, binary trees, binary search trees, and AVL and B-Trees. 3 Trees Trees are recursive data structures. They are useful for:

More information

Binary Search Trees Treesort

Binary Search Trees Treesort Treesort CS 311 Data Structures and Algorithms Lecture Slides Friday, November 13, 2009 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks CHAPPELLG@member.ams.org 2005 2009

More information

Friday Four Square! 4:15PM, Outside Gates

Friday Four Square! 4:15PM, Outside Gates Binary Search Trees Friday Four Square! 4:15PM, Outside Gates Implementing Set On Monday and Wednesday, we saw how to implement the Map and Lexicon, respectively. Let's now turn our attention to the Set.

More information

CSCI-1200 Data Structures Fall 2017 Lecture 18 Trees, Part II

CSCI-1200 Data Structures Fall 2017 Lecture 18 Trees, Part II CSCI-1200 Data Structures Fall 2017 Lecture 18 Trees, Part II Review from Lecture 17 and Lab 9 Binary Trees, Binary Search Trees, & Balanced Trees STL set container class (like STL map, but without the

More information

Trees can be used to store entire records from a database, serving as an in-memory representation of the collection of records in a file.

Trees can be used to store entire records from a database, serving as an in-memory representation of the collection of records in a file. Large Trees 1 Trees can be used to store entire records from a database, serving as an in-memory representation of the collection of records in a file. Trees can also be used to store indices of the collection

More information

Data Structures and Algorithms for Engineers

Data Structures and Algorithms for Engineers 04-630 Data Structures and Algorithms for Engineers David Vernon Carnegie Mellon University Africa vernon@cmu.edu www.vernon.eu Data Structures and Algorithms for Engineers 1 Carnegie Mellon University

More information

1 Binary trees. 1 Binary search trees. 1 Traversal. 1 Insertion. 1 An empty structure is an empty tree.

1 Binary trees. 1 Binary search trees. 1 Traversal. 1 Insertion. 1 An empty structure is an empty tree. Unit 6: Binary Trees Part 1 Engineering 4892: Data Structures Faculty of Engineering & Applied Science Memorial University of Newfoundland July 11, 2011 1 Binary trees 1 Binary search trees Analysis of

More information

CSE 250 Final Exam. Fall 2013 Time: 3 hours. Dec 11, No electronic devices of any kind. You can open your textbook and notes

CSE 250 Final Exam. Fall 2013 Time: 3 hours. Dec 11, No electronic devices of any kind. You can open your textbook and notes CSE 250 Final Exam Fall 2013 Time: 3 hours. Dec 11, 2013 Total points: 100 14 pages Please use the space provided for each question, and the back of the page if you need to. Please do not use any extra

More information

CMSC 341. Binary Search Trees CMSC 341 BST

CMSC 341. Binary Search Trees CMSC 341 BST CMSC 341 Binary Search Trees CMSC 341 BST Announcements Homework #3 dues Thursday (10/5/2017) Exam #1 next Thursday (10/12/2017) CMSC 341 BST A Generic Tree CMSC 341 BST Binary Tree CMSC 341 BST The Binary

More information

A set of nodes (or vertices) with a single starting point

A set of nodes (or vertices) with a single starting point Binary Search Trees Understand tree terminology Understand and implement tree traversals Define the binary search tree property Implement binary search trees Implement the TreeSort algorithm 2 A set of

More information

Binary Search Trees. See Section 11.1 of the text.

Binary Search Trees. See Section 11.1 of the text. Binary Search Trees See Section 11.1 of the text. Consider the following Binary Search Tree 17 This tree has a nice property: for every node, all of the nodes in its left subtree have values less than

More information

Tree: non-recursive definition. Trees, Binary Search Trees, and Heaps. Tree: recursive definition. Tree: example.

Tree: non-recursive definition. Trees, Binary Search Trees, and Heaps. Tree: recursive definition. Tree: example. Trees, Binary Search Trees, and Heaps CS 5301 Fall 2013 Jill Seaman Tree: non-recursive definition Tree: set of nodes and directed edges - root: one node is distinguished as the root - Every node (except

More information

Lecture 34. Wednesday, April 6 CS 215 Fundamentals of Programming II - Lecture 34 1

Lecture 34. Wednesday, April 6 CS 215 Fundamentals of Programming II - Lecture 34 1 Lecture 34 Log into Linux. Copy files on csserver from /home/hwang/cs215/lecture33/*.* In order to compile these files, also need bintree.h from last class. Project 7 posted. Due next week Friday, but

More information

Motivation Computer Information Systems Storage Retrieval Updates. Binary Search Trees. OrderedStructures. Binary Search Tree

Motivation Computer Information Systems Storage Retrieval Updates. Binary Search Trees. OrderedStructures. Binary Search Tree Binary Search Trees CMPUT 115 - Lecture Department of Computing Science University of Alberta Revised 21-Mar-05 In this lecture we study an important data structure: Binary Search Tree (BST) Motivation

More information

Lecture Notes on Binary Search Trees

Lecture Notes on Binary Search Trees Lecture Notes on Binary Search Trees 15-122: Principles of Imperative Computation Tom Cortina Lecture 15 October 14, 2010 1 Introduction In the previous two lectures we have seen how to exploit the structure

More information

Spring 2018 Mentoring 8: March 14, Binary Trees

Spring 2018 Mentoring 8: March 14, Binary Trees CSM 6B Binary Trees Spring 08 Mentoring 8: March 4, 08 Binary Trees. Define a procedure, height, which takes in a Node and outputs the height of the tree. Recall that the height of a leaf node is 0. private

More information

Figure 1. A breadth-first traversal.

Figure 1. A breadth-first traversal. 4.3 Tree Traversals Stepping, or iterating, through the entries of a linearly ordered list has only two obvious orders: from front to back or from back to front. There is no obvious traversal of a general

More information

Lecture 5. Treaps Find, insert, delete, split, and join in treaps Randomized search trees Randomized search tree time costs

Lecture 5. Treaps Find, insert, delete, split, and join in treaps Randomized search trees Randomized search tree time costs Lecture 5 Treaps Find, insert, delete, split, and join in treaps Randomized search trees Randomized search tree time costs Reading: Randomized Search Trees by Aragon & Seidel, Algorithmica 1996, http://sims.berkeley.edu/~aragon/pubs/rst96.pdf;

More information

Lec 17 April 8. Topics: binary Trees expression trees. (Chapter 5 of text)

Lec 17 April 8. Topics: binary Trees expression trees. (Chapter 5 of text) Lec 17 April 8 Topics: binary Trees expression trees Binary Search Trees (Chapter 5 of text) Trees Linear access time of linked lists is prohibitive Heap can t support search in O(log N) time. (takes O(N)

More information

6. Asymptotics: The Big-O and Other Notations

6. Asymptotics: The Big-O and Other Notations Chapter 7 SEARCHING 1. Introduction, Notation 2. Sequential Search 3. Binary Search 4. Comparison Trees 5. Lower Bounds 6. Asymptotics: The Big-O and Other Notations Outline Transp. 1, Chapter 7, Searching

More information

CSCI-1200 Data Structures Fall 2014 Lecture 18 Trees, Part III

CSCI-1200 Data Structures Fall 2014 Lecture 18 Trees, Part III Review from Lecture 17 CSCI-1200 Data Structures Fall 2014 Lecture 18 Trees, Part III Overview of the ds set implementation begin, find, destroy_tree, insert In-order, pre-order, and post-order traversal;

More information

Binary Trees. Height 1

Binary Trees. Height 1 Binary Trees Definitions A tree is a finite set of one or more nodes that shows parent-child relationship such that There is a special node called root Remaining nodes are portioned into subsets T1,T2,T3.

More information

3. Priority Queues. ADT Stack : LIFO. ADT Queue : FIFO. ADT Priority Queue : pick the element with the lowest (or highest) priority.

3. Priority Queues. ADT Stack : LIFO. ADT Queue : FIFO. ADT Priority Queue : pick the element with the lowest (or highest) priority. 3. Priority Queues 3. Priority Queues ADT Stack : LIFO. ADT Queue : FIFO. ADT Priority Queue : pick the element with the lowest (or highest) priority. Malek Mouhoub, CS340 Winter 2007 1 3. Priority Queues

More information

Lecture Notes on Binary Search Trees

Lecture Notes on Binary Search Trees Lecture Notes on Binary Search Trees 15-122: Principles of Imperative Computation Frank Pfenning Lecture 17 1 Introduction In the previous two lectures we have seen how to exploit the structure of binary

More information

Trees. CSE 373 Data Structures

Trees. CSE 373 Data Structures Trees CSE 373 Data Structures Readings Reading Chapter 7 Trees 2 Why Do We Need Trees? Lists, Stacks, and Queues are linear relationships Information often contains hierarchical relationships File directories

More information

Computational Optimization ISE 407. Lecture 16. Dr. Ted Ralphs

Computational Optimization ISE 407. Lecture 16. Dr. Ted Ralphs Computational Optimization ISE 407 Lecture 16 Dr. Ted Ralphs ISE 407 Lecture 16 1 References for Today s Lecture Required reading Sections 6.5-6.7 References CLRS Chapter 22 R. Sedgewick, Algorithms in

More information

LECTURE 18 AVL TREES

LECTURE 18 AVL TREES DATA STRUCTURES AND ALGORITHMS LECTURE 18 AVL TREES IMRAN IHSAN ASSISTANT PROFESSOR AIR UNIVERSITY, ISLAMABAD PROTOTYPICAL EXAMPLES These two examples demonstrate how we can correct for imbalances: starting

More information

IX. Binary Trees (Chapter 10)

IX. Binary Trees (Chapter 10) IX. Binary Trees (Chapter 10) -1- A. Introduction: Searching a linked list. 1. Linear Search /* To linear search a list for a particular Item */ 1. Set Loc = 0; 2. Repeat the following: a. If Loc >= length

More information

Binary Search Trees, etc.

Binary Search Trees, etc. Chapter 12 Binary Search Trees, etc. Binary Search trees are data structures that support a variety of dynamic set operations, e.g., Search, Minimum, Maximum, Predecessors, Successors, Insert, and Delete.

More information

CS 171: Introduction to Computer Science II. Binary Search Trees

CS 171: Introduction to Computer Science II. Binary Search Trees CS 171: Introduction to Computer Science II Binary Search Trees Binary Search Trees Symbol table applications BST definitions and terminologies Search and insert Traversal Ordered operations Delete Symbol

More information

Recall: Properties of B-Trees

Recall: Properties of B-Trees CSE 326 Lecture 10: B-Trees and Heaps It s lunch time what s cookin? B-Trees Insert/Delete Examples and Run Time Analysis Summary of Search Trees Introduction to Heaps and Priority Queues Covered in Chapters

More information

Tree Travsersals and BST Iterators

Tree Travsersals and BST Iterators Tree Travsersals and BST Iterators PIC 10B May 25, 2016 PIC 10B Tree Travsersals and BST Iterators May 25, 2016 1 / 17 Overview of Lecture 1 Sorting a BST 2 In-Order Travsersal 3 Pre-Order Traversal 4

More information

Dynamic Access Binary Search Trees

Dynamic Access Binary Search Trees Dynamic Access Binary Search Trees 1 * are self-adjusting binary search trees in which the shape of the tree is changed based upon the accesses performed upon the elements. When an element of a splay tree

More information

examines every node of a list until a matching node is found, or until all nodes have been examined and no match is found.

examines every node of a list until a matching node is found, or until all nodes have been examined and no match is found. A examines every node of a list until a matching node is found, or until all nodes have been examined and no match is found. For very long lists that are frequently searched, this can take a large amount

More information

Exercise 1 : B-Trees [ =17pts]

Exercise 1 : B-Trees [ =17pts] CS - Fall 003 Assignment Due : Thu November 7 (written part), Tue Dec 0 (programming part) Exercise : B-Trees [+++3+=7pts] 3 0 3 3 3 0 Figure : B-Tree. Consider the B-Tree of figure.. What are the values

More information