1 / 37

Main Index

CSE 331 – Lecture 16. 1. Main Index. Contents. Chapter 10 Binary Search Tree Locating a Node Inserting a Node Removing a Leaf Removing a non-leaf 1 child 2 children. BSTree Iterator Begin End Operator++ Operator* Summary Slides Demo tsimND Discuss Traffic Simulation.

trilby
Download Presentation

Main Index

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CSE 331 – Lecture 16 1 Main Index Contents • Chapter 10 • Binary Search Tree • Locating a Node • Inserting a Node • Removing a Leaf • Removing a non-leaf • 1 child • 2 children • BSTree Iterator • Begin • End • Operator++ • Operator* • Summary Slides • Demo tsimND • Discuss Traffic Simulation

  2. STree Node Class template <typename T> class stnode { public: // public data simplifies building class functions T nodeValue; stnode<T> *left, *right, *parent; // default constructor. data not initialized tnode() {} // initialize the data members stnode (const T& item, stnode<T> *lptr = NULL, stnode<T> *rptr = NULL, stnode<T> *pptr = NULL) : nodeValue(item), left(lptr), right(rptr), parent(pptr) {} };

  3. Binary Search Tree Definition • A binary search tree T is • (a) a binary tree, and • (b) each and every internal node R and its children (CL and CR), if they exist, have values such that valueCL < valueR <= valueCR

  4. 4 Main Index Contents Binary Search Trees

  5. stree(); Create an empty search tree. CLASS stree CLASS stree “d_stree.h” “d_stree.h” Constructors Opertions stree(T *first, T *last); Create a search tree with the elements from the pointer range [first, last). void displayTree(int maxCharacters); Display the search tree. The maximum number of characters needed to output a node value is maxCharacters. bool empty(); Return true if the tree is empty and false otherwise. 5 Main Index Contents

  6. int erase(const T& item); Search the tree and remove item, if it is present; otherwise, take no action. Return the number of elements removed. Postcondition: If item is located in the tree, the size of the tree decreases by 1. CLASS stree “d_stree.h” Opertions void erase(iterator pos); Erase the item pointed to the iterator pos. Precondition: The tree is not empty and pos points to an item in the tree. If the iterator is invalid, the function throws the referenceError exception. Postcondition: The tree size decreases by 1. 6 Main Index Contents

  7. void erase(iterator first, iterator last); Remove all items in the iterator range [first, last). Precondition: The tree is not empty. If empty, the function throws the underflowError exception. Postcondition: The size of the tree decreases by the number of items in the range. CLASS stree “d_stree.h” Opertions iterator find(const T& item); Search the tree by comparing item with the data values in a path of nodes from the root of the tree. If a match occurs, return an iterator pointing to the matching value in the tree. If item is not in the tree, return the iterator value end(). 7 Main Index Contents

  8. Pair<iterator, bool> insert(const T& item); If item is not in the tree, insert it and return an iterator- bool pair where the iterator is the location of the newelement and the Boolean value is true. If item is already in the tree, return the pair where the iterator locates the existing item and the Boolean value is false. Postcondition: The size of the tree is increased by 1 if item is not present in the tree. CLASS stree “d_stree.h” Opertions int size(); Return the number of elements in the tree. 8 Main Index Contents

  9. FindNode() function template <typename T> stnode<T> *stree<T>::findNode(const T& item) const { // cycle t through the tree starting with root stnode<T> *t = root; // terminate on on empty subtree while(t != NULL && !(item == t->nodeValue)) if (item < t->nodeValue) t = t->left; else t = t->right; // return pointer to node; NULL if not found return t; }

  10. Stree find() function template <typename T> stree<T>::iterator stree<T>::find(const T& item) { stnode<T> *curr; // search tree for item curr = findNode (item); // if item found, return iterator with value current; // otherwise, return end() if (curr != NULL) return iterator(curr, this); else return end(); }

  11. Inserting into search tree • All insertions are as LEAVES If tree is empty insert new node here Else if new value == node value return without inserting Else if new value < node value insert in left subtree Else if new value > node value insert in right subtree

  12. Insert() function template <typename T> pair<stree<T>::iterator, bool> stree<T>::insert(const T& item) { stnode<T> *t = root, *parent = NULL, *newNode; while(t != NULL) { parent = t; if (item == t->nodeValue) // found a match return pair<iterator, bool> (iterator(t,this),false); else if (item < t->nodeValue) t = t->left; else t = t->right; } newNode = getSTNode(item,NULL,NULL,parent); if (parent == NULL) // insert as root node root = newNode; else if (item < parent->nodeValue) // insert as left child parent->left = newNode; else // insert as right child parent->right = newNode; treeSize++; return pair<iterator, bool> (iterator(newNode, this), true); }

  13. 13 Main Index Contents Insertion: 1st of 3 steps 1)- The function begins at the root node and compares item 32 with the root value 25. Since 32 > 25, we traverse the right subtree and look at node 35.

  14. 14 Main Index Contents Insertion: 2nd of 3 steps 2)- Considering 35 to be the root of its own subtree, we compare item 32 with 35 and traverse the left subtree of 35.

  15. 15 Main Index Contents Insertion: 3rd of 3 steps 1)- Create a leaf node with data value 32. Insert the new node as the left child of node 35. newNode = getSTNode(item,NULL,NULL,parent); parent->left = newNode;

  16. Deleting a node • Three cases • (1) node that is a leaf • Just delete it • (2) node with single child • Delete node and replace it in tree with its child • (3) node with two children • Find inorder successor • This will be a leaf or a node with only a Right child • Swap value of node and its inorder successor • Delete successor node (now case 1 or 2)

  17. Erase() function 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; if (treeSize == 0) throw underflowError("stree erase(): tree is empty"); if (dNodePtr == NULL) throw referenceError("stree erase(): invalid iterator"); // assign pNodePtr the address of P pNodePtr = dNodePtr->parent; // now determine which case deletion we have // leaf node or node with single child (easy cases) // or node with 2 children (hard case) // continued ....

  18. Erase() // If D has a NULL pointer, the // replacement node is the other child if (dNodePtr->left == NULL || dNodePtr->right == NULL) { if (dNodePtr->right == NULL) rNodePtr = dNodePtr->left; // replacement: left child else rNodePtr = dNodePtr->right;// replacement: right child if (rNodePtr != NULL) // the parent of R is now the parent of D rNodePtr->parent = pNodePtr; } else // node has two children { // find inorder successor, right & then all the way left stnode<T> *pOfRNodePtr = dNodePtr; // parent of successor rNodePtr = dNodePtr->right; // step right while(rNodePtr->left != NULL) { pOfRNodePtr = rNodePtr; rNodePtr = rNodePtr->left; // step left ... }

  19. Erase() if (pOfRNodePtr == dNodePtr) { // right child of deleted node is the replacement. rNodePtr->left = dNodePtr->left; rNodePtr->parent = pNodePtr; dNodePtr->left->parent = rNodePtr; } else { // we moved at least one node down a left branch // of the right child of D. link right subtree of R // as left subtree of parent of R pOfRNodePtr->left = rNodePtr->right; if (rNodePtr->right != NULL) rNodePtr->right->parent = pOfRNodePtr; // link R to D’s children and parent rNodePtr->left = dNodePtr->left; rNodePtr->right = dNodePtr->right; rNodePtr->parent = pNodePtr; rNodePtr->left->parent = rNodePtr; rNodePtr->right->parent = rNodePtr; } }

  20. Erase() // finally, connect R as correct child of parent node of D // if deleting the root node. assign new root if (pNodePtr == NULL) root = rNodePtr; // else attach R as correct child of P else if (dNodePtr->nodeValue < pNodePtr->nodeValue) pNodePtr->left = rNodePtr; else pNodePtr->right = rNodePtr; // delete the node from memory and decrement tree size delete dNodePtr; treeSize--; }

  21. 21 Main Index Contents Removing an Item From a Binary Tree

  22. 22 Main Index Contents Removing an Item From a Binary Tree

  23. 23 Main Index Contents Removing an Item From a Binary Tree

  24. 24 Main Index Contents Removing an Item From a Binary Tree

  25. 25 Main Index Contents Removing an Item From a Binary Tree

  26. 26 Main Index Contents Removing an Item From a Binary Tree

  27. Stree Iterators • Perform INORDER traversals of tree • Iterator and const_iterator are implemented as contained classes within Stree class • See “d_stree.h” and d_siter.h” • Iterator is a two part object with pointer to root of Stree and to current Stnode (see below) private: stnode<T> *nodePtr; // current location in tree stree<T> *tree; // the tree // used to construct an iterator return value // from an stnode pointer iterator (stnode<T> *p, stree<T> *t) : nodePtr(p), tree(t) {}

  28. Stree begin() function template <typename T> stree<T>::iterator stree<T>::begin() { stnode<T> *curr = root; // if the tree is not empty, the first node // inorder is the farthest node left from root if (curr != NULL) while (curr->left != NULL) curr = curr->left; // build return value using private constructor return iterator(curr, this); }

  29. Stree end() function template <typename T> stree<T>::iterator stree<T>::end() { // end indicated by iterator with NULL stnode pointer return iterator(NULL, this); }

  30. Siter operator++() - preincrement iterator& operator++ () // preincrement. move forward inorder { stnode<T> *p; if (nodePtr == NULL) // ++ from end() { nodePtr = tree->root; // start at root if (nodePtr == NULL) throw underflowError("stree iter op++ (): t empty"); // move to smallest value in tree, 1st node inorder while (nodePtr->left != NULL) nodePtr = nodePtr->left; } else if (nodePtr->right != NULL) { // find successor { nodePtr = nodePtr->right; // step right while (nodePtr->left != NULL) nodePtr = nodePtr->left; // go all the way left } else // move up the tree, looking for a parent having { // *nodePtr is left child p = nodePtr->parent; while (p != NULL && nodePtr == p->right) { nodePtr = p; p = p->parent; } nodePtr = p; // now, either p is NULL or *p is the successor } return *this; }

  31. Siter operator++(int) - postincrement iterator operator++ (int) // postincrement { // save current iterator iterator tmp = *this; // move myself forward to the next tree node ++*this; // return the previous value return tmp; }

  32. 32 Main Index Contents Summary Slide 1 §-trees - hierarchical structures that place elements in nodes along branches that originate from a root. - Nodes in a tree are subdivided into levels in which the topmost level holds the root node. §- Any node in a tree may have multiple successors at the next level. Hence a tree is a non-linear structure. - Tree terminology with which you should be familiar: parent | child | descendents | leaf node | interior node | subtree.

  33. 33 Main Index Contents Summary Slide 2 §-Binary Trees - Most effective as a storage structure if it has high density §- ie: data are located on relatively short paths from the root. §-A complete binary tree has the highest possible density - an n-node complete binary tree has depth int(log2n). - At the other extreme, a degenerate binary tree is equivalent to a linked list and exhibits O(n) access times.

  34. 34 Main Index Contents Summary Slide 3 §-Traversing Through a Tree - There are six simple recursive algorithms for tree traversal. - The most commonly used ones are: 1) inorder (LNR) 2) postorder (LRN) 3) preorder (NLR). - Another technique is to move left to right from level to level. §- This algorithm is iterative, and its implementation involves using a queue.

  35. 35 Main Index Contents Summary Slide 4 §-A binary search tree stores data by value instead of position - It is an example of an associative container. §- The simple rules “== return” “< go left” “> go right” until finding a NULL subtree make it easy to build a binary search tree that does not allow duplicate values.

  36. 36 Main Index Contents Summary Slide 5 §- The insertion algorithm can be used to define the path to locate a data value in the tree. §- The removal of an item from a binary search tree is more difficult and involves finding a replacement node among the remaining values.

  37. 37 Main Index Contents Summary Slide 6 §- Iterators traverse the Stree INORDER. Stree functions begin() and end() set initial iterator values, while ++ and – operators are iterator functions. §- Iterators may be implemented as imbedded classes within the BStree class.

More Related