CSE 2123 Recursion. Jeremy Morris

Similar documents
C22a: Problem Solving using Recursion

Binary Trees

CSE 2123: Collections: Priority Queues. Jeremy Morris

Postfix (and prefix) notation

Data Structures and Algorithms

q To develop recursive methods for recursive mathematical functions ( ).

q To develop recursive methods for recursive mathematical functions ( ).

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

Recursion. Genome 559: Introduction to Statistical and Computational Genomics Elhanan Borenstein

CSE 143 Lecture 11. Decimal Numbers

COMP 250 Fall recurrences 2 Oct. 13, 2017

CSE 143. Computer Programming II

COMP 202 Recursion. CONTENTS: Recursion. COMP Recursion 1

CS/CE 2336 Computer Science II

CSE 332 Autumn 2013: Midterm Exam (closed book, closed notes, no calculators)

Announcements. Recursion and why study it. Recursive programming. Recursion basic idea

A6-R3: DATA STRUCTURE THROUGH C LANGUAGE

ITI Introduction to Computing II

Programming and Data Structure

CS 171: Introduction to Computer Science II. Quicksort

Lecture 15 Binary Search Trees

ITI Introduction to Computing II

Counting Problems; and Recursion! CSCI 2824, Fall 2012!

[1] Strings, Arrays, Pointers, and Hashing

Building Java Programs

Data Structures and Algorithms Dr. Naveen Garg Department of Computer Science and Engineering Indian Institute of Technology, Delhi.

CSE Data Structures and Introduction to Algorithms... In Java! Instructor: Fei Wang. Mid-Term Exam. CSE2100 DS & Algorithms 1

Solving Linear Recurrence Relations (8.2)

INSTITUTE OF AERONAUTICAL ENGINEERING

Solving problems by recursion

R10 SET - 1. Code No: R II B. Tech I Semester, Supplementary Examinations, May

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

Lecture Notes on Binary Search Trees

8/5/10 TODAY'S OUTLINE. Recursion COMP 10 EXPLORING COMPUTER SCIENCE. Revisit search and sorting using recursion. Recursion WHAT DOES THIS CODE DO?

Wentworth Institute of Technology COMP1050 Computer Science II Spring 2017 Derbinsky. Recursion. Lecture 13. Recursion

COMP Lecture Notes Iterative and Recursive Procedures for Strings

COMP-202. Recursion. COMP Recursion, 2013 Jörg Kienzle and others

Lecture 15 Notes Binary Search Trees

We cover recursion in 150. Why do it again in 151?

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

12/30/2013 S. NALINI,AP/CSE

Data Structures and Algorithms

Recursion. Recursion is: Recursion splits a problem:

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

Fun facts about recursion

Advanced Java Concepts Unit 5: Trees. Notes and Exercises

Pointers, References and Arrays

In addition to the correct answer, you MUST show all your work in order to receive full credit.

COMP-202. Recursion. COMP Recursion, 2011 Jörg Kienzle and others

CSE11 Lecture 20 Fall 2013 Recursion

Recursion is a fundamental programming technique that can provide an elegant solution certain kinds of problems. COMP Week 8 & 9 1

COMP : Trees. COMP20012 Trees 219

CMPSCI 187: Programming With Data Structures. Lecture #34: Efficient Sorting Algorithms David Mix Barrington 3 December 2012

Admin. How's the project coming? After these slides, read chapter 13 in your book. Quizzes will return

Recursion. Tracing Method Calls via a Stack. Beyond this lecture...

CS24 Week 8 Lecture 1

a graph is a data structure made up of nodes in graph theory the links are normally called edges

CS F-11 B-Trees 1

University of the Western Cape Department of Computer Science

Recursion: Factorial (1) Recursion. Recursion: Principle. Recursion: Factorial (2) Recall the formal definition of calculating the n factorial:

Assignment 1. Stefano Guerra. October 11, The following observation follows directly from the definition of in order and pre order traversal:

CMSC 341 Lecture 10 Binary Search Trees

CMPSCI 187: Programming With Data Structures. Lecture #26: Binary Search Trees David Mix Barrington 9 November 2012

Lecture Notes 14 More sorting CSS Data Structures and Object-Oriented Programming Professor Clark F. Olson

Section 05: Solutions

Recursion. Chapter 7. Copyright 2012 by Pearson Education, Inc. All rights reserved

Trees. A tree is a directed graph with the property

CSCI 262 Data Structures. Recursive Function Analysis. Analyzing Power. Analyzing Power. Analyzing Power 3/31/2018

INF2220: algorithms and data structures Series 1

Computer Science 210 Data Structures Siena College Fall Topic Notes: Trees

CS211, LECTURE 20 SEARCH TREES ANNOUNCEMENTS:

CSE 373 OCTOBER 25 TH B-TREES

Spring 2018 Mentoring 8: March 14, Binary Trees

COSC 2007 Data Structures II Final Exam. Part 1: multiple choice (1 mark each, total 30 marks, circle the correct answer)

Recursion. EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG

CSE 373: Data Structures and Algorithms

Programming II (CS300)

Announcement. Submit assignment 3 on CourSys Do not hand in hard copy Due Friday, 15:20:00. Caution: Assignment 4 will be due next Wednesday

CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees. CS 135 Winter 2018 Tutorial 7: Accumulative Recursion and Binary Trees 1

Multi-way Search Trees! M-Way Search! M-Way Search Trees Representation!

Recursion. Recursion [Bono] 1

Data Structures and Organization (p.5 Recursion. Binary Trees)

/633 Introduction to Algorithms Lecturer: Michael Dinitz Topic: Priority Queues / Heaps Date: 9/27/17

R10 SET - 1. Code No: R II B. Tech I Semester, Supplementary Examinations, May

2.3 Recursion. Overview. Mathematical Induction. What is recursion? When one function calls itself directly or indirectly.

Algorithm classification

Greedy Algorithms CHAPTER 16

Lecture 11: Recursion (hard)

26 How Many Times Must a White Dove Sail...

CmpSci 187: Programming with Data Structures Spring 2015

(Refer Slide Time: 01.26)

CSE 5095 Topics in Big Data Analytics Spring 2014; Homework 1 Solutions

Hanoi, Counting and Sierpinski s triangle Infinite complexity in finite area

1 Dynamic Programming

Lecture 24 Tao Wang 1

Complexity, Induction, and Recurrence Relations. CSE 373 Help Session 4/7/2016

1. O(log n), because at worst you will only need to downheap the height of the heap.

1 Dynamic Programming

DUKE UNIVERSITY Department of Computer Science. Test 2: CompSci 100

Lecture Notes on Binary Search Trees

Transcription:

CSE 2123 Recursion Jeremy Morris 1

Past Few Weeks For the past few weeks we have been focusing on data structures Classes & Object-oriented programming Collections Lists, Sets, Maps, etc. Now we turn our attention to algorithms Algorithm: specific process for solving a problem Specifically recursive algorithms, search algorithms, and sorting algorithms 2

Recursion Recursive methods Methods that call themselves Recall that a method performs a specific task A recursive method performs a specific task by calling itself to do it How is that going to work? 3

Example: reverse a String Suppose we want to write a method to reverse a String: /* * @param str the String to be reversed * @return the reverse of str */ public static String reverse(string str) 4

Example: reverse a String Suppose we want to write a method to reverse a String: We could do this with an iterative approach: /* * @param str the String to be reversed * @return the reverse of str */ public static String reverse(string str) { String rev = ; for (int i=0; i<str.length(); i++) { rev = str.charat(i)+rev; } return rev; } 5

Example: reverse a String But suppose we have a static method that will already do most of the work for us? reversestring will reverse almost any String Except - we have to make our problem smaller first it won t work on our String Specifically, we can t do this: public static String reverse(string str) { return reversestring(str); } 6

Recursive Thinking Subproblems Recursive problems often have this kind of subproblem structure The big problem you re trying to solve is actually a smaller problem that is exactly the same as the big problem, combined with a simple additional step For the reverse a String problem, we can recognize: reverse(str) == reverse(str.substring(1,str.length())) +str.charat(0); 7

Recursive Thinking Subproblems For the reverse a String problem, we can recognize: reverse(str) == reverse(str.substring(1,str.length())) + str.charat(0); So if we have some way to reverse a String of length 8, we could reverse a String of length 9 by: Removing the first character Reversing the String that s left Appending the first character to the end of our reversed substring 8

Recursive Thinking Subproblems For the reverse a String problem, we can recognize: reverse(str) = reverse(str.substring(1,str.length())) + str.charat(0); So if we have some way to reverse a String of length 8, we could reverse a String of length 9 by: This is our subproblem! Removing the first character Reversing the String that s left Appending the first character to the end of our reversed substring 9

Example: reverse a String So here s how we can use that reversestring method: public static String reverse(string str) { String sub = str.substring(1,str.length()); String rev = reversestring(sub); rev = rev + str.charat(0); return rev; } 10

Example: reverse a String So here s how we can use that reversestring method: Does this code work for all input Strings? What test cases will make this code fail? public static String reverse(string str) { String sub = str.substring(1,str.length()); String rev = reversestring(sub); rev = rev + str.charat(0); return rev; } 11

Example: reverse a String So here s how we can use that reversestring method: Does this code work for all input Strings? What test cases will make this code fail? public static String reverse(string str) { String sub = str.substring(1,str.length()); String rev = reversestring(sub); rev = rev + str.charat(0); return rev; } What about empty ( ) Strings? 12

Example: reverse a String This code takes care of our bad test case: public static String reverse(string str) { if (str.length() == 0) { return str; } else { String sub = str.substring(1,str.length()); String rev = reversestring(sub); rev = rev + str.charat(0); return rev; } } 13

Example: reverse a String Okay, so that works IF we have a method that solves our subproblem for us But we don t or do we? What is a subproblem? a smaller problem that is exactly the same as the larger problem, combined with an extra step We have a method that solves the bigger problem Let s call it to solve the smaller problem 14

Example: reverse a String This code is recursive: public static String reverse(string str) { if (str.length() == 0) { return str; } else { String sub = str.substring(1,str.length()); String rev = reverse(sub); rev = rev + str.charat(0); return rev; } } 15

Example: reverse a String This code is recursive: public static String reverse(string str) { if (str.length() == 0) { return str; } else { String sub = str.substring(1,str.length()); String rev = reverse(sub); rev = rev + str.charat(0); return rev; } } The method calls itself! 16

Recursion If your code for a method is correct when it calls a hypothetical helper method that solves a smaller subproblem for it Then it is also correct when you replace that helper method with a call to the method itself! But this only works if you make the problem smaller That is crucial for recursive thinking you have to be working on a subproblem Recursive solutions are only guaranteed to work if you make the problem smaller each time! 17

Another Example: raise to a power Suppose we want to write a method to raise an integer to an integer power: /* * @param n the base to be raised * @param p the integer power > 0 to rase n to * @return n^p */ public static int power(int n, int p) 18

Another example: raise to a power What s the hidden subproblem here? Think about this can we break this up into a smaller problem that is exactly the same as our original problem (but smaller) and one extra step? n p =? 19

Another example: raise to a power What s the hidden subproblem here? Think about this can we break this up into a smaller problem that is exactly the same as our original problem (but smaller) and one extra step? n p = n * n p-1 20

Another example: raise to a power /* * @param n the base to be raised * @param p the integer power > 0 to rase n to * @return n^p */ public static int power(int n, int p) n p = n * n p-1 How can we write a recursive power method using this? 21

Another example: raise to a power /* * @param n the base to be raised * @param p the integer power > 0 to rase n to * @return n^p */ public static int power(int n, int p) A different smaller problem n p = (n p/2 ) 2 (If p>1 and p is even) How can we write a different recursive power method using this? There s often more than one way to solve a problem! Which of these implementations is faster? 22

Properties of recursion Recursive methods will have two cases: The general case This is the recursive call to itself This is where we make the problem smaller and use our method to solve that smaller problem The base case This is the non-recursive case This is where the problem is as small as it is going to get and we need to solve it The simplest case. 23

Example: reverse a String public static String reverse(string str) { if (str.length() == 0) { return str; } else { String sub = str.substring(1,str.length()); String rev = reverse(sub); rev = rev + str.charat(0); return rev; } } 24

Example: reverse a String public static String reverse(string str) { if (str.length() == 0) { return str; Base Case } else { String sub = str.substring(1,str.length()); String rev = reverse(sub); rev = rev + str.charat(0); return rev; } } 25

Example: reverse a String public static String reverse(string str) { if (str.length() == 0) { return str; } else { String sub = str.substring(1,str.length()); String rev = reverse(sub); rev = rev + str.charat(0); return rev; } } General Case 26

Example: reverse a String public static String reverse(string str) { if (str.length() == 0) { return str; } else { String sub = str.substring(1,str.length()); String rev = reverse(sub); rev = rev + str.charat(0); return rev; } } Recursive Call 27

Uses of recursion I Recursion is often used to solve these Divide and Conquer problems Solve a larger problem by: Divide: Split problem into one or more smaller subproblems Conquer: Solve the smaller problems Combine: Merge smaller solutions into larger solution Example: reverse Divide: Split into subproblems: reverse of smaller substring Base case: stop when length of String is 0 Conquer: Compute reverse of smaller string and reverse of first character Combine: append first character to the end of the reversed substring 28

Class Example - sumarray Write a recursive method named sumarray public static int sumarray(int[] a, int left, int right) Returns the sum of all values between left and right in the array a How do we solve this recursively? What is our subproblem? What is our base case? 29

Class Example - onlypositive Write a recursive method named onlypositive public static boolean onlypositive(int[] a, int left, int right) Returns true if all values between left and right in the array a are positive Otherwise, returns false How do we solve this recursively? What is our subproblem? What is our base case? 30

Class Example - countchar Write a recursive method named countchar public static int countchar(string str, char c) Returns a count of number of times character c occurs in String str Hint: Use str.charat(), str.substring(), and str.length() Divide & Conquer Base Case? General Case? 31

Class Example - issorted Write a recursive method named issorted public static boolean issorted(int[] a, int left, int right) Returns true if all values between left and right in the array a are in increasing order Otherwise, returns false Divide & Conquer What is our subproblem? What is our Base Case? 32

Class Example - ispalindrome Write a recursive method named ispalindrome public static boolean ispalindrome(string str) Returns true if the String str is a palindrome Otherwise, returns false Divide & Conquer What is our subproblem? What is our base case? 33

Uses of recursion II Recursion is also needed when we deal with trees Why might this be the case? Trees are an example of a recursive data structure! How are trees recursive? Each tree has a root node that has some number of children. Each child node also has some number of children So each child node can be viewed as if it were the root of a new tree A tree is therefore a root node and a collection of subtrees branching off that root node 34

Back to the Binary Tree Recall the binary tree structure 10 Each node in the tree has up to 2 children (binary) 3 19 1 7 22 35

Back to the Binary Tree Recall the binary tree structure 10 Each node in the tree has up to 2 children (binary) 3 19 We can view each child node as the root of its own tree 1 7 22 36

Back to the Binary Tree Recall the binary tree structure 10 Each node in the tree has up to 2 children (binary) 3 19 We can view each child node as the root of its own tree 1 7 22 And its children as the roots of their own trees 37

Back to the Binary Tree Recall the binary tree structure 10 Each node in the tree has up to 2 children (binary) 3 19 We can view each child node as the root of its own tree 1 7 22 And its children as the roots of their own trees And so on 38

Recursion on Trees Recursive algorithms are often easy to implement on trees In fact, sometimes the recursive algorithm is the easiest way to do something with a tree And trees show up a lot in a computer science context We ve already seen binary search trees And how useful they are for Maps, Sets, Priority Queues HTML documents use a tree model Databases use trees to store data 39

Recursion on Trees Let s consider the simple task of just counting all of the nodes in binary search tree We might think of this as counting all of the descendants of the root node children, grandchildren, great-grandchildren, etc., plus the root node itself How would we do this? Let s consider how we might approach this iteratively without recursion 40

Counting nodes How would you write a while loop to count the nodes in this tree? 3 10 19 1 7 22 41

Counting nodes How would you write a while loop to count the nodes in this tree? 3 10 19 Now, will your loop still work if we do this? 1 7 22 Or do we need to do something else now? 5 9 42

Counting nodes Now let s think of a recursive solution 10 One that exploits the fact that each child node is the root of its own tree 3 19 What is our subproblem? 1 7 22 What is our base case? 43

Counting Nodes public static int countnodes(node n) { } 44

Recursion on Trees Now consider the task of visiting every node in a binary search tree in order That is, turning a search tree into a sorted list by getting the elements in the proper order How would we do this? Let s consider how we might approach this iteratively 45

Traversing the Tree How would you write a while loop to traverse this tree? 10 Will it work if we change the tree to something bigger? Smaller? 1 3 7 19 22 46

Traversing the Tree Now let s think of a recursive solution 10 One that exploits the fact that each child node is the root of its own tree 3 19 What is our subproblem? 1 7 22 What is our base case? 47

Traverse the tree public static void traverse(node n) { } 48

Recursion on Trees Next let s consider the task of inserting a new node into the tree How can we add a node to the proper place in the tree? Let s consider how we might approach this iteratively 49

Inserting into the Tree Suppose we want to insert a value 10 How would you use a while loop to insert into this tree? 3 19 Will your solution work if we change the tree? 1 7 22 50

Inserting into the Tree Now let s think of a recursive solution 10 One that exploits the fact that each child node is the root of its own tree 3 19 What is our subproblem? 1 7 22 What is our base case? 51

Insert into the tree public static void insert(node root, int n) { } 52

Recursion on Trees Trees are an example where recursion is not just useful, it s better than the alternative Sometimes we will have a choice of approaches with an algorithm We could use an iterative approach or a recursive approach The one we use will be the one that most naturally fits the problem But other times we don t have much choice we must use the recursive approach Trees are an example of this 53

Understanding Recursion- Toy Problem Sometimes, we like to use toy problem to help us understand an idea Simple problems like reversing a String are examples of toy problems They re not terribly interesting A famous toy problem for recursion is the Towers of Hanoi problem 54

Towers of Hanoi In the Towers of Hanoi problem there are three posts 55

Towers of Hanoi In the Towers of Hanoi problem there are three posts On one post is a set of discs of different sizes 56

Towers of Hanoi In the Towers of Hanoi problem there are three posts On one post is a set of discs of different sizes The goal is to move all of the discs from the first post to the last post 57

Towers of Hanoi In the Towers of Hanoi problem there are three posts On one post is a set of discs of different sizes The goal is to move all of the discs from the first post to the last post 58

Towers of Hanoi The goal is to move all of the discs from the first post to the last post BUT it isn t that easy 59

Towers of Hanoi The goal is to move all of the discs from the first post to the last post BUT it isn t that easy We can only move the discs one at a time And no disc can be on top of a smaller disc How are we going to do this? 60

Towers of Hanoi How are we going to do this? The key is to grasp the recursive nature of this problem To move 5 discs to the last peg, we must first move 4 discs to the middle peg 61

Towers of Hanoi How are we going to do this? The key is to grasp the recursive nature of this problem To move 5 discs to the last peg, we must first move 4 discs to the middle peg 62

Towers of Hanoi How are we going to do this? The key is to grasp the recursive nature of this problem To move 5 discs to the last peg, we must first move 4 discs to the middle peg Then move the big disc to the last peg 63

Towers of Hanoi How are we going to do this? The key is to grasp the recursive nature of this problem To move 5 discs to the last peg, we must first move 4 discs to the middle peg Then move the big disc to the last peg Then move 4 discs to the last peg 64

Towers of Hanoi Okay, how do we move 4 discs to the middle peg? First we move 3 discs to the last peg 65

Towers of Hanoi Okay, how do we move 4 discs to the middle peg? First we move 3 discs to the last peg Then the fourth disc to the middle peg 66

Towers of Hanoi Okay, how do we move 4 discs to the middle peg? First we move 3 discs to the last peg Then the fourth disc to the middle peg Then the three discs to the middle peg 67

Towers of Hanoi Okay, how do we move 4 discs to the middle peg? First we move 3 discs to the last peg Then the fourth disc to the middle peg Then the three discs to the middle peg 68

Towers of Hanoi Okay, how do we move 3 discs to the last peg? First we move 2 discs to the middle peg 69

Towers of Hanoi Okay, how do we move 3 discs to the last peg? First we move 2 discs to the middle peg 70

Towers of Hanoi Okay, how do we move 3 discs to the last peg? First we move 2 discs to the middle peg Then the third disc to the last peg 71

Towers of Hanoi Okay, how do we move 3 discs to the last peg? First we move 2 discs to the middle peg Then the third disc to the last peg Then the two discs to the last peg 72

Towers of Hanoi Okay, how do we move 2 discs to the middle peg? First we move 1 disc to the last peg 73

Towers of Hanoi Okay, how do we move 2 discs to the middle peg? First we move 1 disc to the last peg Then we move the second disc to the middle peg 74

Towers of Hanoi Okay, how do we move 2 discs to the middle peg? First we move 1 disc to the last peg Then we move the second disc to the middle peg Then the 1 disc to the middle peg 75

Towers of Hanoi Okay, how do we move 2 discs to the middle peg? First we move 1 disc to the last peg Then we move the second disc to the middle peg Then the 1 disc to the middle peg 76

Towers of Hanoi Okay, how do we move 1 disc to the last peg? Wait that s easy! We just move the disc! 77

Towers of Hanoi Okay, how do we move 1 disc to the last peg? Wait that s easy! We just move the disc! 78

Towers of Hanoi So what is our recursive structure here? What is our base case? What is our general case? 79

Towers Of Hanoi Let s write a recursive method for the Towers of Hanoi The method should print out a series of steps like: Move disk 1 from peg 1 to peg 3 Move disk 2 from peg 1 to peg 2 Move disk 1 from peg 3 to peg 2 (These would be if we had two discs and wanted to move them to the middle peg) public static void move(int disks, int from, int to, int spare) 80