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