EXERCISES SOFTWARE DEVELOPMENT I. 10 Recursion, Binary (Search) Trees Towers of Hanoi // Tree Traversal 2018W

Similar documents
SOFTWARE DEVELOPMENT 1. Recursion 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)

CS 231 Data Structures and Algorithms Fall Binary Search Trees Lecture 23 October 29, Prof. Zadia Codabux

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

Lecture 26. Introduction to Trees. Trees

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

Data Structures and Algorithms

Advanced Java Concepts Unit 5: Trees. Notes and Exercises

Programming II (CS300)

Computing Science 115 Final Examination April 23, 2002 Section: B2 BASU. Please put student id on last page. Instructions:

Chapter 20: Binary Trees

Tree Structures. A hierarchical data structure whose point of entry is the root node

Recursion Chapter 17. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

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

CS350: Data Structures Tree Traversal

TREES. Trees - Introduction

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100 Department of Electronics and Communication

Also, recursive methods are usually declared private, and require a public non-recursive method to initiate them.

Title Description Participants Textbook

Recursive Definitions

ITEC2620 Introduction to Data Structures

3 Trees: traversal and analysis of standard search trees

INF2220: algorithms and data structures Series 1

» Access elements of a container sequentially without exposing the underlying representation

Tree. A path is a connected sequence of edges. A tree topology is acyclic there is no loop.

Prepared By: Ms. Nidhi Solanki (Assist. Prof.) Page 1

Recursion. COMS W1007 Introduction to Computer Science. Christopher Conway 26 June 2003

CSCI-401 Examlet #5. Name: Class: Date: True/False Indicate whether the sentence or statement is true or false.

F453 Module 7: Programming Techniques. 7.2: Methods for defining syntax

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

Advanced Java Concepts Unit 5: Trees. Notes and Exercises

Binary Trees: Practice Problems

17CS33:Data Structures Using C QUESTION BANK

Data Structure - Binary Tree 1 -

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

Two Approaches to Algorithms An Example (1) Iteration (2) Recursion

STUDENT LESSON AB30 Binary Search Trees

CS61B Lecture #20: Trees. Last modified: Mon Oct 8 21:21: CS61B: Lecture #20 1

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

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

Abstract Data Structures IB Computer Science. Content developed by Dartford Grammar School Computer Science Department

Name CPTR246 Spring '17 (100 total points) Exam 3

3 Trees: traversal and analysis of standard search trees. Summer Term 2010

University of Palestine. Final Exam 2 nd semester 2014/2015 Total Grade: 50

FINALTERM EXAMINATION Fall 2009 CS301- Data Structures Question No: 1 ( Marks: 1 ) - Please choose one The data of the problem is of 2GB and the hard

About This Lecture. Trees. Outline. Recursive List Definition slide 1. Recursive Tree Definition. Recursive List Definition slide 2

Recursion. Let s start by looking at some problems that are nicely solved using recursion. First, let s look at generating The Fibonacci series.

Data Structures. Trees. By Dr. Mohammad Ali H. Eljinini. M.A. Eljinini, PhD

Introduction to Trees. D. Thiebaut CSC212 Fall 2014

9/26/2018 Data Structure & Algorithm. Assignment04: 3 parts Quiz: recursion, insertionsort, trees Basic concept: Linked-List Priority queues Heaps

Recursion. Data and File Structures Laboratory. DFS Lab (ISI) Recursion 1 / 27

Recursion. Example 1: Fibonacci Numbers 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,

CS2012 Programming Techniques II

1.7 Recursion. Department of CSE

CS134 Spring 2005 Final Exam Mon. June. 20, 2005 Signature: Question # Out Of Marks Marker Total

IX. Binary Trees (Chapter 10)

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

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

CS61B Lecture #20: Trees. Last modified: Wed Oct 12 12:49: CS61B: Lecture #20 1

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

MLR Institute of Technology

Summer Final Exam Review Session August 5, 2009

Chapter 6 Recursion. The Concept of Recursion

R13. II B. Tech I Semester Supplementary Examinations, May/June DATA STRUCTURES (Com. to ECE, CSE, EIE, IT, ECC)

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

CSCS-200 Data Structure and Algorithms. Lecture

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

CS171 Final Practice Exam

Building Java Programs

CE 221 Data Structures and Algorithms

Binary Trees

BRONX COMMUNITY COLLEGE of the City University of New York DEPARTMENT OF MATHEMATICS AND COMPUTER SCIENCE. Sample Final Exam

Data Structures And Algorithms

Data Structure Lecture#10: Binary Trees (Chapter 5) U Kang Seoul National University

Chapter 15: Recursion

recursive algorithms 1

Algorithms and Data Structures

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

CS 206 Introduction to Computer Science II

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

CSE 2123 Recursion. Jeremy Morris

Class 27: Nested Classes and an Introduction to Trees

Recursion CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2011

CS171 Final Practice Exam

C22a: Problem Solving using Recursion

Trees! Ellen Walker! CPSC 201 Data Structures! Hiram College!

Introduction to Algorithms and Data Structures

Recursion. Chapter 5

Binary Trees. Examples:

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

Recursion. Overview. Mathematical induction. Hello recursion. Recursion. Example applications. Goal: Compute factorial N! = 1 * 2 * 3...

Give one example where you might wish to use a three dimensional array

Round and round recursion: the good, the bad, the ugly, the hidden

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

Data Structures And Algorithms

Binary Trees, Binary Search Trees

cs Java: lecture #6

Trees. Dr. Ronaldo Menezes Hugo Serrano Ronaldo Menezes, Florida Tech

CS 180 Problem Solving and Object Oriented Programming Fall 2011

Binary Tree. Binary tree terminology. Binary tree terminology Definition and Applications of Binary Trees

Figure 18.4 A Unix directory. 02/13/03 Lecture 11 1

Transcription:

EXERCISES SOFTWARE DEVELOPMENT I 10 Recursion, Binary (Search) Trees Towers of Hanoi // Tree Traversal 2018W

Recursion

I RECURSION :: MOTIVATION AND DEFINITION Many complex real-world problems can be solved very elegantly by using recursive algorithms, e.g., compact in terms of LOC (lines of code) in particular true for mathematical problems (where the problem itself is formulated recursively, e.g., Fibonacci numbers, calculation of the Factorial, etc.) Sort algorithms (traversal of binary tree, etc.) Recursion [Definition] Method that calls itself directly or indirect Basic elements termination condition (anchor of the recursive function; used for escaping) recursive (function) calls (altered parameter!!!) Indirect recursion two or more functions calls each other (in a loop ) at least one of these functions is declared as recursive function (termination condition/anchor) Recursive defined solutions are mostly less efficient than iterative programs; why? Recursive functions are in general more easy to read/understand as compared to iterative solutions Software Development I // 2018W // 3

I RECURSION :: BASIC STRUCTURE DIRECT Recursion () n Terminate? Processing1 Recursion () y Processing2 Recursion () if (TerminationCondition) // Recursion anchor Processing2; else Processing1; Recursion (); Recursive call Software Development I // 2018W // 4

RECURSION :: BASIC STRUCTURE (2) INDIRECT Recursion () n Terminate? y Function () Processing1 Processing2 Function () Processing3 Recursion () Software Development I // 2018W // 5

RECURSION :: TRANSFORMATION ITERATION RECURSION Example: Sum of numbers from 0 (zero) to max. (including) public class RecursionTest private static int sumiterative (int max) int k = 0; for (int i = max; i > 0; i--) k += i; return k; public static void main(string[] args) //... sumiterative(5); System.out.println(sumIterative(5)); //... run time check: 9000: Recursive algorithmus (val=9000) took longer by (ms): 2 9999: Exception in thread "main" java.lang.stackoverflowerror at RecursionTest.sumRecursive(RecursionTest.java:18) public class RecursionTest private static int sumrecursive (int i) if (i <= 0) return 0; return i + sumrecursive (i - 1); public static void main(string[] args) //... sumrecursive(5); System.out.println(sumRecursive(5)); //... note the altered parameter Software Development I // 2018W // 6

RECURSION :: TRANSFORMATION ITERATION RECURSION General procedure for/while loop A change to ifcondition A() Termination? yes yes yes Termination? Termination? Processing Processing Processing goto A A() Software Development I // 2018W // 7

EXAMPLE :: SEQUENCE OF NUMBERS Given is the following sequence of numbers F = 5, 8, 11, 14,... We are looking for different solutions to retrieve the value of the sequence by providing the index of the number to the function, i.e., f(<0) = -1, // error condition f(0) = 5, f(1) = 8, f(2) = 11, etc. Algorithms are seeked for Java programs using a) iterative technique, b) recursion, c) direct calculation Software Development I // 2018W // 8

EXAMPLE :: SEQUENCE OF NUMBERS Solution a) Iterative... int f (int i) int y = 5; if (i < 0) return -1; for (; i > 0; i--) y += 3; return y; Software Development I // 2018W // 9

EXAMPLE :: SEQUENCE OF NUMBERS Solution a) b) With branch instruction ('GOTO')... int f (int i) int y = 5; if (i < 0) return -1; A: if (i == 0) return y; y += 3; i = i-1; goto A; Software Development I // 2018W // 10

EXAMPLE :: SEQUENCE OF NUMBERS Solution b) Recursive... int f (int i) if (i < 0) return -1; Termination condition (recursion anchor) if (i == 0) return 5; int y = f (i - 1) + 3; return y; Recursive call Software Development I // 2018W // 11

EXAMPLE :: SEQUENCE OF NUMBERS Solution c) Calculation (Formula)... int f (int i) if (i < 0) return -1; return 5 + 3 * i; Finding: Recursive algorithm is NOT always the most efficient one or the one executing fastest Software Development I // 2018W // 12

I RECURSION :: TOWERS OF HANOI This problem comes from history Monks in Vietnam were asked to carry 64 gold disks from one tower (stack) to another. Each disk is of a different size. There are 3 stacks, a source stack, a destination stack and an intermediate stack. A disk is placed on one of three stacks but no disk can be placed on top of a smaller disk. The source tower holds 64 disks. How will the monks solve this problem? How long will it take them? Software Development I // 2018W // 13

RECURSION :: TOWERS OF HANOI The easist solution is a recursive one The key to the solution is to notice that to move any disk, we must first move the smaller disks off of it, thus a recursive definition. Another way to look at it is this, if we had a method to move the top three disks to the middle position, we could put the biggest disk in its place. All we need to do is assume we have this method and then call it 0 1 2 Start 1 2 3 4 5 End Software Development I // 2018W // 15 1 2 3 4 5

RECURSION :: TOWERS OF HANOI Recursive problem definition Lets start with 1 disk (our base case): Move 1 disk from start tower to destination tower and we are done To move 2 disks: Move smaller disk from start tower to intermediate tower, move larger disk from start tower to final tower, move smaller disk from intermediate tower to final tower and we are done To move n disks (or think of, say, 3 disks): Solve the problem for n - 1 disks (i.e., 2 disks) using the intermediate tower instead of the final tower (i.e., get 2 disks onto the intermediate tower). Then, move the biggest disk from start tower to final tower Then again solve the problem for n - 1 disks but use the intermediate tower instead of the start tower (i.e., get the 2 disks onto the final tower using the start tower as the intermediate tower) Software Development I // 2018W // 16

RECURSION :: TOWERS OF HANOI 1 2 1' 2' 3' Software Development I // 2018W // 17

RECURSION :: TOWERS OF HANOI 1 2 1' 2' 3' Software Development I // 2018W // 18

RECURSION :: TOWERS OF HANOI 2 1' 1'' 2'' 3'' Software Development I // 2018W // 19

RECURSION :: TOWERS OF HANOI 2 1' 1'' 2'' 3'' Software Development I // 2018W // 20

RECURSION :: TOWERS OF HANOI 2 1' 1''' 2''' 3''' Software Development I // 2018W // 21

RECURSION :: TOWERS OF HANOI Developing a general solution T (n, a, b) n height of the tower a initial stack b destination stack To move a tower of height 5 from 0 to 2: T (5, 0, 2) = T (4, 0, 1) + D (0, 2) + T (4, 1, 2) To move a tower of height 4 from 0 to 1: T (4,0, 1) = T (3, 0, 2) + D (0, 1) + T (3, 2, 1) Modulo operation on stacks To move a tower of height n T (n, a, b) = T (n-1, a, 3-(a+b)) + D (a, b) + T (n-1, 3-(a+b), b) Software Development I // 2018W // 22

RECURSION :: TOWERS OF HANOI Java solution public class TowerOfHanoi public static void D (int h, int a, int b) System.out.println("Disc " + h + " from " + a + " to " + b); public static void T (int h, int a, int b) if (h > 0) T (h - 1, a, 3 - (a+b)); D (h, a, b); T (h - 1, 3 - (a+b), b); public static void main(string[] args) T (3, 0, 2); 15/01/2014 Execution times (with output of disc movement) Tower of Hanoi (height=10) took (sec): 0.029 Tower of Hanoi (height=15) took (sec): 0.341 Tower of Hanoi (height=20) took (sec): 11 Tower of Hanoi (height=25) took (sec): 425 Tower of Hanoi (height=30) took (sec): 58722 (>16h) Software Development I // 2018W // 23

I RECURSION :: BINARY (SEARCH) TREES Binary Tree [Definition] A binary tree is either empty (null) (=default case) or it consists of a node K with an associated element E (=data) and two binary (sub)trees B 1 and B 2 Note the recursive definition! K K K B 1 E B 2 E E B B B Software Development I // 2018W // 24

RECURSION :: BINARY (SEARCH) TREES Java implementation public class Tree Object element; // more general: int value; Tree left, right; public static final Tree EMPTY = new Tree(); public Tree () element = null; // value=0; etc. left = null; right = null; public Tree (Tree left, Object element, Tree right) this.element = element; this.left = left; this.right = right; public Tree (Object element) this(empty, element, EMPTY); public boolean empty () return (element == null); public Tree left () if (empty()) System.err.println("left: empty tree"); return left; public Tree right () if (empty()) System.err.println("right: empty tree"); return right; public Object getelement () if (empty()) System.err.println("element: empty"); return element; err The "standard" error output stream. By convention, this output stream is used to display error messages and typically this stream corresponds to display output specified by the host environment or user. Software Development I // 2018W // 25

I RECURSION :: BINARY SEARCH TREE Definition 'Binary Search Tree': A binary search tree is a binary tree with sorted elements Elements/values in the left sub-tree are always "smaller" than the node element (i.e., B 1.element < B.element), elements in the right sub-tree are "equal or greater" as compared to the (base) node (B 2.element >= B.element) "Root" Linz K Node B 1 B 2 Enns E Wels B Bruck Graz Leaves Software Development I // 2018W // 26

I RECURSION :: BINARY SEARCH TREE Common operations create a new binary (search) tree insert a node (element) search/lookup for a node (element) traversal (iterate over all elements) delete a node (element) Tree traversal Directed iteration over all elements of the tree Three options Preorder traversal Inorder traversal Postorder traversal All the 3 options may be implemented recursively Software Development I // 2018W // 27

RECURSION :: BINARY SEARCH TREE insert() operation (sample code) Tree insert (Tree rootnode, Tree atree) if (rootnode == null) return atree; if (rootnode.isequal(atree)) System.out.println("Node already in tree (ignored)"); // atree.visit(0); return rootnode; Note the recursive definition! if (rootnode.isgreaterthan(atree)) rootnode.left = insert (rootnode.left, atree); return rootnode; else rootnode.right = insert (rootnode.right, atree); return rootnode; Software Development I // 2018W // 28

RECURSION :: BINARY SEARCH TREE Preorder traversal Visit the root node Visit left sub-tree (preorder traversal) Visit right sub-tree (preorder traversal) Order of node visits Java sample code 2 3 4 1 5 6 7 public static void preorder (Tree b) if (!b.empty()) System.out.println (b.value()); preorder (b.left()); preorder (b.right()); Software Development I // 2018W // 29

RECURSION :: BINARY SEARCH TREE Inorder traversal Visit left sub-tree (inorder traversal) Visit the root node Visit right sub-tree (inorder traversal) Order of node visits Java sample code 2 1 3 4 6 5 7 public static void inorder (Tree b) if (!b.empty()) inorder (b.left()); System.out.println (b.value()); inorder (b.right()); Output: All elements are sorted ascending Software Development I // 2018W // 30

RECURSION :: BINARY SEARCH TREE Postorder traversal Visit left sub-tree (postorder traversal) Visit right sub-tree (postorder traversal) Visit the root node Order of node visits Java sample code 3 1 2 7 6 4 5 public static void postorder (Tree b) if (!b.empty()) postorder (b.left()); postorder (b.right()); System.out.println (b.value()); Software Development I // 2018W // 31

Software Development I // 2016W // 32

EXERCISES SOFTWARE DEVELOPMENT I 10 Recursion, Binary (Search) Trees Towers of Hanoi // Tree Traversal 2018W