1 / 66

C++ Plus Data Structures

C++ Plus Data Structures. Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus. Recursive Function Call.

kelli
Télécharger la présentation

C++ Plus Data Structures

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. C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus

  2. Recursive Function Call • A recursive call is a function call in which the called function is the same as the one making the call. • In other words, recursion occurs when a function calls itself! • We must avoid making an infinite sequence of function calls (infinite recursion).

  3. Finding a Recursive Solution • Each successive recursive call should bring you closer to a situation in which the answer is known. • A case for which the answer is known (and can be expressed without recursion) is called a base case. • Each recursivealgorithm must have at least one base case, as well as the general (recursive) case

  4. Three-Question Method of verifying recursive functions • Base-Case Question: Is there a nonrecursive way out of the function? • Smaller-Caller Question: Does each recursive function call involve a smaller case of the original problem leading to the base case? • General-Case Question: Assuming each recursive call works correctly, does the whole function work correctly?

  5. Writing Recursive Functions • Get an exact definition of the problem to be solved. • Determine the size of the problem on this call to the function. • Identify and solve the base case(s). • Identify and solve the general case(s) in terms of a smaller case of the same problem – a recursive call.

  6. “Why use recursion?” Those examples could have been written without recursion, using iteration instead. The iterative solution uses a loop, and the recursive solution uses an if statement. However, for certain problems the recursive solution is the most natural solution. This often occurs when pointer variables are used.

  7. Recursive Linked List Processing

  8. struct ListType struct NodeType { int info ; NodeType* next ; } class SortedType { public : . . . // member function prototypes private : NodeType* listData ; } ;

  9. A B C D E FIRST, print out this section of list, backwards THEN, print this element RevPrint(listData); listData

  10. Base Case and General Case A base case may be a solution in terms of a “smaller” list. Certainly for a list with 0 elements, there is no more processing to do. Our general case needs to bring us closer to the base case situation. That is, the number of list elements to be processed decreases by 1 with each recursive call. By printing one element in the general case, and also processing the smaller remaining list, we will eventually reach the situation where 0 list elements are left to be processed. In the general case, we will print the elements of the smaller remaining list in reverse order, and then print the current pointed to element.

  11. Using recursion with a linked list void RevPrint ( NodeType* listPtr ) // Pre: listPtr points to an element of a list. // Post: all elements of list pointed to by listPtr have been printed // out in reverse order. { if ( listPtr != NULL ) // general case { RevPrint ( listPtr-> next ) ; // process the rest cout << listPtr->info << endl ; // then print this element } // Base case : if the list is empty, do nothing } 11

  12. How Recursion Works • Static storage allocation associates variable names with memory locations at compile time. • Dynamic storage allocation associates variable names with memory locations at execution time.

  13. When a function is called... • A transfer of control occurs from the calling block to the code of the function. It is necessary that there is a return to the correct place in the calling block after the function code is executed. This correct place is called the return address. • When any function is called, the run-time stack is used. On this stack is placed an activation record (stack frame) for the function call.

  14. Stack Activation Frames • The activation record stores the return address for this function call, and also the parameters, local variables, and the function’s return value, if non-void. • The activation record for a particular function call is popped off the run-time stack when the final closing brace in the function code is reached, or when a return statement is reached in the function code. • At this time the function’s return value, if non-void, is brought back to the calling block return address for use there.

  15. Debugging Recursive Routines • Using the Three-Question Method. • Using a branching statement (if/switch). • Put debug output statement during testing. • …

  16. Removing Recursion When the language doesn’t support recursion, or recursive solution is too costly (space or time), or … • Iteration • Stacking

  17. Use a recursive solution when: • The depth of recursive calls is relatively “shallow” compared to the size of the problem. • The recursive version does about the same amount of work as the nonrecursive version. • The recursive version is shorter and simpler than the nonrecursive solution. SHALLOW DEPTH EFFICIENCY CLARITY

  18. C++ Plus Data Structures Nell Dale Chapter 8 Binary Search Trees Modified from the slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus

  19. Binary search for an element in a sorted list stored sequentially • in an array: O(Log2N) • in a linked list: ? (midpoint = ?)

  20. Goals of this chapter • Introduce some basic tree vocabulary • Develop algorithms • Implement operations needed to use a binary search tree

  21. Binary Tree A binary tree is a structure in which: Each node can have at most two children, and in which a unique path exists from the root to every other node. The two children of a node are called the left child and the right child, if they exist.

  22. Implementing a Binary Tree with Pointers and Dynamic Data V Q L T A E K S

  23. Each node contains two pointers template< class ItemType > struct TreeNode { ItemType info;// Data member TreeNode<ItemType>* left;// Pointer to left child TreeNode<ItemType>* right; // Pointer to right child }; NULL ‘A’6000 .left .info .right

  24. // BINARY SEARCH TREE SPECIFICATION template< class ItemType > class TreeType { public: TreeType ( ); // constructor ~TreeType ( ); // destructor bool IsEmpty ( ) const; bool IsFull ( ) const; int NumberOfNodes ( ) const; void InsertItem ( ItemType item ); void DeleteItem (ItemType item ); void RetrieveItem ( ItemType& item, bool& found ); void PrintTree (ofstream& outFile) const; . . . private: TreeNode<ItemType>* root; }; 24

  25. ‘J’ TreeType ~TreeType ‘S’ ‘E’ IsEmpty InsertItem ‘H’ ‘A’ TreeType<char> CharBST; Private data: root RetrieveItem PrintTree . . .

  26. A Binary Tree V Q L T A E K S Search for ‘S’?

  27. A Binary Search Tree (BST) is . . . A special kind of binary tree in which: 1. Each node contains a distinct data value, 2. The key values in the tree can be compared using “greater than” and “less than”, and 3. The key value of each node in the tree is less than every key value in its right subtree, and greater than every key value in its left subtree.

  28. ‘D’ ‘Z’ ‘K’ ‘B’ ‘L’ ‘Q’ ‘S’ Is ‘F’ in the binary search tree? ‘J’ ‘T’ ‘E’ ‘A’ ‘V’ ‘M’ ‘H’ ‘P’

  29. ‘D’ ‘Z’ ‘K’ ‘B’ ‘L’ ‘Q’ ‘S’ Is ‘F’ in the binary search tree? ‘J’ ‘T’ ‘E’ ‘A’ ‘V’ ‘M’ ‘H’ ‘P’

  30. // BINARY SEARCH TREE SPECIFICATION template< class ItemType > class TreeType { public: TreeType ( ) ; // constructor ~TreeType ( ) ; // destructor bool IsEmpty ( ) const ; bool IsFull ( ) const ; int NumberOfNodes ( ) const ; void InsertItem ( ItemType item ) ; void DeleteItem (ItemType item ) ; void RetrieveItem ( ItemType& item , bool& found ) ; void PrintTree (ofstream& outFile) const ; . . . private: TreeNode<ItemType>* root ; }; 30

  31. // SPECIFICATION (continued) // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // RECURSIVE PARTNERS OF MEMBER FUNCTIONS template< class ItemType > void PrintHelper ( TreeNode<ItemType>* ptr, ofstream& outFile ) ; template< class ItemType > void InsertHelper ( TreeNode<ItemType>*& ptr, ItemType item ) ; template< class ItemType > void RetrieveHelper (TreeNode<ItemType>* ptr, ItemType& item, bool& found ) ; template< class ItemType > void DestroyHelper ( TreeNode<ItemType>* ptr ) ; 31

  32. template< class ItemType > void TreeType<ItemType> :: RetrieveItem ( ItemType& item, bool& found ) { RetrieveHelper ( root, item, found ) ; } template< class ItemType > void RetrieveHelper ( TreeNode<ItemType>* ptr, ItemType& item, bool& found) { if ( ptr == NULL ) found = false ; else if ( item < ptr->info ) // GO LEFT RetrieveHelper( ptr->left , item, found ) ; else if ( item > ptr->info ) // GO RIGHT RetrieveHelper( ptr->right , item, found ) ; else { item = ptr->info ; found = true ; } } 32

  33. template< class ItemType > void TreeType<ItemType> :: InsertItem ( ItemType item ) { InsertHelper ( root, item ) ; } template< class ItemType > void InsertHelper ( TreeNode<ItemType>*& ptr, ItemType item ) { if ( ptr == NULL ) { // INSERT item HERE AS LEAF ptr = new TreeNode<ItemType> ; ptr->right = NULL ; ptr->left = NULL ; ptr->info = item ; } else if ( item < ptr->info ) // GO LEFT InsertHelper( ptr->left , item ) ; else if ( item > ptr->info ) // GO RIGHT InsertHelper( ptr->right , item ) ; } 33

  34. PrintTree() Traverse a list: -- forward -- backward Traverse a tree: -- there are many ways!

  35. ‘J’ Inorder Traversal: A E H J M T Y Print second tree ‘T’ ‘E’ ‘A’ ‘H’ ‘M’ ‘Y’ Print left subtree first Print right subtree last

  36. ‘J’ Preorder Traversal: J E A H T M Y Print first tree ‘T’ ‘E’ ‘A’ ‘H’ ‘M’ ‘Y’ Print left subtree second Print right subtree last

  37. ‘J’ Postorder Traversal: A H E M Y T J Print last tree ‘T’ ‘E’ ‘A’ ‘H’ ‘M’ ‘Y’ Print left subtree first Print right subtree second

  38. Recursion or Iteration? Assume: the tree is well balanced. • Is the depth of recursion relatively shallow? Yes. • Is the recursive solution shorter or clearer than the nonrecursive version? Yes. • Is the recursive version much less efficient than the nonrecursive version? No.

  39. Use a recursive solution when (Chpt. 7): • The depth of recursive calls is relatively “shallow” compared to the size of the problem. • The recursive version does about the same amount of work as the nonrecursive version. • The recursive version is shorter and simpler than the nonrecursive solution. SHALLOW DEPTH EFFICIENCY CLARITY

  40. Binary Search Trees (BSTs) vs. Linear Lists BST: • Quick random-access with the flexibility of a linked structure • Can be implemented elegantly and concisely using recursion • Takes up more memory space than a singly linked list • Algorithms are more complicated

  41. C++ Plus Data Structures Nell Dale Chapter 9 Trees Plus Modified from the slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus

  42. A Binary Expression Tree is . . . A special kind of binary tree in which: 1. Each leaf node contains a single operand, 2. Each nonleaf node contains asingle binary operator, and 3. The left and right subtrees of an operator node represent subexpressions that must be evaluated before applying the operator at the root of the subtree.

  43. Levels Indicate Precedence When a binary expression tree is used to represent an expression, the levels of the nodes in the tree indicate their relative precedence of evaluation. Operations at higher levels of the tree are evaluated later than those below them.The operation at the root is always the last operation performed.

  44. ‘*’ ‘3’ ‘+’ ‘2’ ‘4’ A Binary Expression Tree Infix: ( ( 4 + 2 ) * 3 ) Prefix: * + 4 2 3 Postfix: 4 2 + 3 * has operators in order used

  45. ‘/’ Inorder Traversal: (A + H) / (M - Y) Print second tree ‘-’ ‘+’ ‘A’ ‘H’ ‘M’ ‘Y’ Print left subtree first Print right subtree last

  46. ‘/’ Preorder Traversal: / + A H - M Y Print first tree ‘-’ ‘+’ ‘A’ ‘H’ ‘M’ ‘Y’ Print left subtree second Print right subtree last

  47. ‘/’ Postorder Traversal: A H + M Y - / Print last tree ‘-’ ‘+’ ‘A’ ‘H’ ‘M’ ‘Y’ Print left subtree first Print right subtree second

  48. Function Eval() • Definition: Evaluates the expression represented by the binary tree. • Size: The number of nodes in the tree. • Base Case: If the content of the node is an operand, Func_value = the value of the operand. • General Case: If the content of the node is an operator BinOperator, • Func_value = Eval(left subtree) • BinOperator • Eval(right subtree)

  49. Writing Recursive Functions (Chpt 7) • Get an exact definition of the problem to be solved. • Determine the size of the problem on this call to the function. • Identify and solve the base case(s). • Identify and solve the general case(s) in terms of a smaller case of the same problem – a recursive call.

  50. Eval(TreeNode * tree) Algorithm: IF Info(tree) is an operand Return Info(tree) ELSE SWITCH(Info(tree)) case + :Return Eval(Left(tree)) + Eval(Right(tree)) case - : Return Eval(Left(tree)) - Eval(Right(tree)) case * : Return Eval(Left(tree)) * Eval(Right(tree)) case / : Return Eval(Left(tree)) / Eval(Right(tree))

More Related