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

Size: px
Start display at page:

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

Transcription

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

2 Recursion

3 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

4 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

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

6 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): : 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

7 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

8 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

9 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

10 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

11 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

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

13 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

14 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 Start End Software Development I // 2018W //

15 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

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

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

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

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

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

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

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): Tower of Hanoi (height=15) took (sec): Tower of Hanoi (height=20) took (sec): 11 Tower of Hanoi (height=25) took (sec): 425 Tower of Hanoi (height=30) took (sec): (>16h) Software Development I // 2018W // 23

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

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

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

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

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

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 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

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 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

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 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

31 Software Development I // 2016W // 32

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

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

SOFTWARE DEVELOPMENT 1. Recursion 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz) SOFTWARE DEVELOPMENT 1 Recursion 2018W (Institute of Pervasive Computing, JKU Linz) PRINCIPLE OF SELF-REFERENCE Recursion: Describing something in a self-similar way. An elegant, powerful and simple way

More information

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

CS 231 Data Structures and Algorithms Fall Binary Search Trees Lecture 23 October 29, Prof. Zadia Codabux CS 231 Data Structures and Algorithms Fall 2018 Binary Search Trees Lecture 23 October 29, 2018 Prof. Zadia Codabux 1 Agenda Ternary Operator Binary Search Tree Node based implementation Complexity 2 Administrative

More information

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

COMP-202. Recursion. COMP Recursion, 2013 Jörg Kienzle and others COMP-202 Recursion Recursion Recursive Definitions Run-time Stacks Recursive Programming Recursion vs. Iteration Indirect Recursion Lecture Outline 2 Recursive Definitions (1) A recursive definition is

More information

Lecture 26. Introduction to Trees. Trees

Lecture 26. Introduction to Trees. Trees Lecture 26 Introduction to Trees Trees Trees are the name given to a versatile group of data structures. They can be used to implement a number of abstract interfaces including the List, but those applications

More information

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

Recursion. Chapter 7. Copyright 2012 by Pearson Education, Inc. All rights reserved Recursion Chapter 7 Contents What Is Recursion? Tracing a Recursive Method Recursive Methods That Return a Value Recursively Processing an Array Recursively Processing a Linked Chain The Time Efficiency

More information

Data Structures and Algorithms

Data Structures and Algorithms Data Structures and Algorithms CS245-2017S-06 Binary Search Trees David Galles Department of Computer Science University of San Francisco 06-0: Ordered List ADT Operations: Insert an element in the list

More information

Advanced Java Concepts Unit 5: Trees. Notes and Exercises

Advanced Java Concepts Unit 5: Trees. Notes and Exercises Advanced Java Concepts Unit 5: Trees. Notes and Exercises A Tree is a data structure like the figure shown below. We don t usually care about unordered trees but that s where we ll start. Later we will

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 11: Binary Search Trees MOUNA KACEM mouna@cs.wisc.edu Fall 2018 General Overview of Data Structures 2 Introduction to trees 3 Tree: Important non-linear data structure

More information

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

Computing Science 115 Final Examination April 23, 2002 Section: B2 BASU. Please put student id on last page. Instructions: Computing Science 115 Final Examination April 23, 2002 Section: B2 BASU Last Name: First Name: Please put student id on last page Instructions: The time for this test is 3 hrs. No references or calculators

More information

Chapter 20: Binary Trees

Chapter 20: Binary Trees Chapter 20: Binary Trees 20.1 Definition and Application of Binary Trees Definition and Application of Binary Trees Binary tree: a nonlinear linked list in which each node may point to 0, 1, or two other

More information

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

Tree Structures. A hierarchical data structure whose point of entry is the root node Binary Trees 1 Tree Structures A tree is A hierarchical data structure whose point of entry is the root node This structure can be partitioned into disjoint subsets These subsets are themselves trees and

More information

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

Recursion Chapter 17. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Recursion Chapter 17 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 2 Scope Introduction to Recursion: The concept of recursion Recursive methods Infinite recursion When to use (and

More information

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

a graph is a data structure made up of nodes in graph theory the links are normally called edges 1 Trees Graphs a graph is a data structure made up of nodes each node stores data each node has links to zero or more nodes in graph theory the links are normally called edges graphs occur frequently in

More information

CS350: Data Structures Tree Traversal

CS350: Data Structures Tree Traversal Tree Traversal James Moscola Department of Engineering & Computer Science York College of Pennsylvania James Moscola Defining Trees Recursively Trees can easily be defined recursively Definition of a binary

More information

TREES. Trees - Introduction

TREES. Trees - Introduction TREES Chapter 6 Trees - Introduction All previous data organizations we've studied are linear each element can have only one predecessor and successor Accessing all elements in a linear sequence is O(n)

More information

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

PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -100 Department of Electronics and Communication USN 1 P E PESIT Bangalore South Campus Hosur road, 1km before Electronic City, Bengaluru -0 Department of Electronics and Communication INTERNAL ASSESSMENT TEST 2 Date : 4//2017 Marks: 50 Subject & Code

More information

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

Also, recursive methods are usually declared private, and require a public non-recursive method to initiate them. Laboratory 11: Expression Trees and Binary Search Trees Introduction Trees are nonlinear objects that link nodes together in a hierarchical fashion. Each node contains a reference to the data object, a

More information

Title Description Participants Textbook

Title Description Participants Textbook Podcast Ch17b Title: Iterative Tree Traversal Description: Iterative tree traversal; the InorderIterator Class; program 17.2 Participants: Barry Kurtz (instructor); John Helfert and Tobie Williams (students)

More information

Recursive Definitions

Recursive Definitions Recursion Objectives Explain the underlying concepts of recursion Examine recursive methods and unravel their processing steps Explain when recursion should and should not be used Demonstrate the use of

More information

ITEC2620 Introduction to Data Structures

ITEC2620 Introduction to Data Structures 9//207 ITEC2620 Introduction to Data Structures Lecture b Recursion and Binary Tree Operations Divide and Conquer Break a problem into smaller subproblems that are easier to solve What happens when the

More information

3 Trees: traversal and analysis of standard search trees

3 Trees: traversal and analysis of standard search trees 3 Trees: traversal and analysis of standard search trees Binary search trees Binary trees for storing sets of keys, such that the operations are supported: - find - insert - delete Search tree property:

More information

INF2220: algorithms and data structures Series 1

INF2220: algorithms and data structures Series 1 Universitetet i Oslo Institutt for Informatikk A. Maus, R.K. Runde, I. Yu INF2220: algorithms and data structures Series 1 Topic Trees & estimation of running time (Exercises with hints for solution) Issued:

More information

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

» Access elements of a container sequentially without exposing the underlying representation Iterator Pattern Behavioural Intent» Access elements of a container sequentially without exposing the underlying representation Iterator-1 Motivation Be able to process all the elements in a container

More information

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

Tree. A path is a connected sequence of edges. A tree topology is acyclic there is no loop. Tree A tree consists of a set of nodes and a set of edges connecting pairs of nodes. A tree has the property that there is exactly one path (no more, no less) between any pair of nodes. A path is a connected

More information

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

Prepared By: Ms. Nidhi Solanki (Assist. Prof.) Page 1 QUESTION BANK ON COURSE: 304: PRELIMINARIES: 1. What is array of pointer, explain with appropriate example? 2 2. Differentiate between call by value and call by reference, give example. 3. Explain pointer

More information

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

Recursion. COMS W1007 Introduction to Computer Science. Christopher Conway 26 June 2003 Recursion COMS W1007 Introduction to Computer Science Christopher Conway 26 June 2003 The Fibonacci Sequence The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, 21, 34,... We can calculate the nth Fibonacci

More information

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

CSCI-401 Examlet #5. Name: Class: Date: True/False Indicate whether the sentence or statement is true or false. Name: Class: Date: CSCI-401 Examlet #5 True/False Indicate whether the sentence or statement is true or false. 1. The root node of the standard binary tree can be drawn anywhere in the tree diagram. 2.

More information

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

F453 Module 7: Programming Techniques. 7.2: Methods for defining syntax 7.2: Methods for defining syntax 2 What this module is about In this module we discuss: explain how functions, procedures and their related variables may be used to develop a program in a structured way,

More information

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

26 How Many Times Must a White Dove Sail... Lecture 26 c 2005 Felleisen, Proulx, et. al. 26 How Many Times Must a White Dove Sail... From Here to Eternity According to an old legend the priests in the Temple of Brahma got the task of measuring the

More information

Advanced Java Concepts Unit 5: Trees. Notes and Exercises

Advanced Java Concepts Unit 5: Trees. Notes and Exercises dvanced Java Concepts Unit 5: Trees. Notes and Exercises Tree is a data structure like the figure shown below. We don t usually care about unordered trees but that s where we ll start. Later we will focus

More information

Binary Trees: Practice Problems

Binary Trees: Practice Problems Binary Trees: Practice Problems College of Computing & Information Technology King Abdulaziz University CPCS-204 Data Structures I Warmup Problem 1: Searching for a node public boolean recursivesearch(int

More information

17CS33:Data Structures Using C QUESTION BANK

17CS33:Data Structures Using C QUESTION BANK 17CS33:Data Structures Using C QUESTION BANK REVIEW OF STRUCTURES AND POINTERS, INTRODUCTION TO SPECIAL FEATURES OF C Learn : Usage of structures, unions - a conventional tool for handling a group of logically

More information

Data Structure - Binary Tree 1 -

Data Structure - Binary Tree 1 - Data Structure - Binary Tree 1 - Hanyang University Jong-Il Park Basic Tree Concepts Logical structures Chap. 2~4 Chap. 5 Chap. 6 Linear list Tree Graph Linear structures Non-linear structures Linear Lists

More information

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR STUDENT IDENTIFICATION NO MULTIMEDIA COLLEGE JALAN GURNEY KIRI 54100 KUALA LUMPUR FIFTH SEMESTER FINAL EXAMINATION, 2014/2015 SESSION PSD2023 ALGORITHM & DATA STRUCTURE DSEW-E-F-2/13 25 MAY 2015 9.00 AM

More information

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

Two Approaches to Algorithms An Example (1) Iteration (2) Recursion 2. Recursion Algorithm Two Approaches to Algorithms (1) Iteration It exploits while-loop, for-loop, repeat-until etc. Classical, conventional, and general approach (2) Recursion Self-function call It exploits

More information

STUDENT LESSON AB30 Binary Search Trees

STUDENT LESSON AB30 Binary Search Trees STUDENT LESSON AB30 Binary Search Trees Java Curriculum for AP Computer Science, Student Lesson AB30 1 STUDENT LESSON AB30 Binary Search Trees INTRODUCTION: A binary tree is a different kind of data structure

More information

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

CS61B Lecture #20: Trees. Last modified: Mon Oct 8 21:21: CS61B: Lecture #20 1 CS61B Lecture #20: Trees Last modified: Mon Oct 8 21:21:22 2018 CS61B: Lecture #20 1 A Recursive Structure Trees naturally represent recursively defined, hierarchical objects with more than one recursive

More information

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

Trees. (Trees) Data Structures and Programming Spring / 28 Trees (Trees) Data Structures and Programming Spring 2018 1 / 28 Trees A tree is a collection of nodes, which can be empty (recursive definition) If not empty, a tree consists of a distinguished node r

More information

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

Recursion. EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG Recursion EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG Recursion: Principle Recursion is useful in expressing solutions to problems that can be recursively defined: Base Cases:

More information

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

Abstract Data Structures IB Computer Science. Content developed by Dartford Grammar School Computer Science Department Abstract Data Structures IB Computer Science Content developed by Dartford Grammar School Computer Science Department HL Topics 1-7, D1-4 1: System design 2: Computer Organisation 3: Networks 4: Computational

More information

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

Name CPTR246 Spring '17 (100 total points) Exam 3 Name CPTR246 Spring '17 (100 total points) Exam 3 1. Linked Lists Consider the following linked list of integers (sorted from lowest to highest) and the changes described. Make the necessary changes in

More information

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

3 Trees: traversal and analysis of standard search trees. Summer Term 2010 3 Trees: traversal and analysis of standard search trees Summer Term 2010 Robert Elsässer Binary Search Trees Binary trees for storing sets of keys (in the internal nodes of trees), such that the operations

More information

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

University of Palestine. Final Exam 2 nd semester 2014/2015 Total Grade: 50 First Question Q1 B1 Choose the best Answer: No. of Branches (1) (10/50) 1) 2) 3) 4) Suppose we start with an empty stack and then perform the following operations: Push (A); Push (B); Pop; Push (C); Top;

More information

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

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 FINALTERM EXAMINATION Fall 2009 CS301- Data Structures Question No: 1 The data of the problem is of 2GB and the hard disk is of 1GB capacity, to solve this problem we should Use better data structures

More information

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

About This Lecture. Trees. Outline. Recursive List Definition slide 1. Recursive Tree Definition. Recursive List Definition slide 2 Revised 21-Mar-05 About This Lecture 2 Trees In this lecture we study a non-linear container called a Tree and a special kind of Tree called a Binary Tree. CMPUT 115 - Lecture 18 Department of Computing

More information

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

Recursion. Let s start by looking at some problems that are nicely solved using recursion. First, let s look at generating The Fibonacci series. Recursion The programs we have discussed so far have been primarily iterative and procedural. Code calls other methods in a hierarchical manner. For some problems, it is very useful to have the methods

More information

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

Data Structures. Trees. By Dr. Mohammad Ali H. Eljinini. M.A. Eljinini, PhD Data Structures Trees By Dr. Mohammad Ali H. Eljinini Trees Are collections of items arranged in a tree like data structure (none linear). Items are stored inside units called nodes. However: We can use

More information

Introduction to Trees. D. Thiebaut CSC212 Fall 2014

Introduction to Trees. D. Thiebaut CSC212 Fall 2014 Introduction to Trees D. Thiebaut CSC212 Fall 2014 A bit of History & Data Visualization: The Book of Trees. (Link) We Concentrate on Binary-Trees, Specifically, Binary-Search Trees (BST) How Will Java

More information

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

9/26/2018 Data Structure & Algorithm. Assignment04: 3 parts Quiz: recursion, insertionsort, trees Basic concept: Linked-List Priority queues Heaps 9/26/2018 Data Structure & Algorithm Assignment04: 3 parts Quiz: recursion, insertionsort, trees Basic concept: Linked-List Priority queues Heaps 1 Quiz 10 points (as stated in the first class meeting)

More information

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

Recursion. Data and File Structures Laboratory.  DFS Lab (ISI) Recursion 1 / 27 Recursion Data and File Structures Laboratory http://www.isical.ac.in/~dfslab/2017/index.html DFS Lab (ISI) Recursion 1 / 27 Definition A recursive function is a function that calls itself. The task should

More information

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

Recursion. Example 1: Fibonacci Numbers 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, Example 1: Fibonacci Numbers 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, Recursion public static long fib(int n) if (n

More information

CS2012 Programming Techniques II

CS2012 Programming Techniques II 14/02/2014 C2012 Programming Techniques II Vasileios Koutavas Lecture 14 1 BTs ordered operations deletion 27 T implementations: summary implementation guarantee average case search insert delete search

More information

1.7 Recursion. Department of CSE

1.7 Recursion. Department of CSE 1.7 Recursion 1 Department of CSE Objectives To learn the concept and usage of Recursion in C Examples of Recursion in C 2 Department of CSE What is recursion? Sometimes, the best way to solve a problem

More information

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

CS134 Spring 2005 Final Exam Mon. June. 20, 2005 Signature: Question # Out Of Marks Marker Total CS134 Spring 2005 Final Exam Mon. June. 20, 2005 Please check your tutorial (TUT) section from the list below: TUT 101: F 11:30, MC 4042 TUT 102: M 10:30, MC 4042 TUT 103: M 11:30, MC 4058 TUT 104: F 10:30,

More information

IX. Binary Trees (Chapter 10)

IX. Binary Trees (Chapter 10) IX. Binary Trees (Chapter 10) -1- A. Introduction: Searching a linked list. 1. Linear Search /* To linear search a list for a particular Item */ 1. Set Loc = 0; 2. Repeat the following: a. If Loc >= length

More information

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

COMP-202. Recursion. COMP Recursion, 2011 Jörg Kienzle and others COMP-202 Recursion Recursion Recursive Definitions Run-time Stacks Recursive Programming Recursion vs. Iteration Indirect Recursion Lecture Outline 2 Recursive Definitions (1) A recursive definition is

More information

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

Recursion: Factorial (1) Recursion. Recursion: Principle. Recursion: Factorial (2) Recall the formal definition of calculating the n factorial: Recursion EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG Recursion: Factorial (1) Recall the formal definition of calculating the n factorial: 1 if n = 0 n! = n (n 1) (n 2) 3 2

More information

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

CS61B Lecture #20: Trees. Last modified: Wed Oct 12 12:49: CS61B: Lecture #20 1 CS61B Lecture #2: Trees Last modified: Wed Oct 12 12:49:46 216 CS61B: Lecture #2 1 A Recursive Structure Trees naturally represent recursively defined, hierarchical objects with more than one recursive

More information

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

CMPSCI 187: Programming With Data Structures. Lecture #26: Binary Search Trees David Mix Barrington 9 November 2012 CMPSCI 187: Programming With Data Structures Lecture #26: Binary Search Trees David Mix Barrington 9 November 2012 Binary Search Trees Why Binary Search Trees? Trees, Binary Trees and Vocabulary The BST

More information

MLR Institute of Technology

MLR Institute of Technology MLR Institute of Technology Laxma Reddy Avenue, Dundigal, Quthbullapur (M), Hyderabad 500 043 Phone Nos: 08418 204066 / 204088, Fax : 08418 204088 TUTORIAL QUESTION BANK Course Name : DATA STRUCTURES Course

More information

Summer Final Exam Review Session August 5, 2009

Summer Final Exam Review Session August 5, 2009 15-111 Summer 2 2009 Final Exam Review Session August 5, 2009 Exam Notes The exam is from 10:30 to 1:30 PM in Wean Hall 5419A. The exam will be primarily conceptual. The major emphasis is on understanding

More information

Chapter 6 Recursion. The Concept of Recursion

Chapter 6 Recursion. The Concept of Recursion Data Structures for Java William H. Ford William R. Topp Chapter 6 Recursion Bret Ford 2005, Prentice Hall The Concept of Recursion An algorithm is recursive if it can be broken into smaller problems of

More information

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

R13. II B. Tech I Semester Supplementary Examinations, May/June DATA STRUCTURES (Com. to ECE, CSE, EIE, IT, ECC) SET - 1 II B. Tech I Semester Supplementary Examinations, May/June - 2016 PART A 1. a) Write a procedure for the Tower of Hanoi problem? b) What you mean by enqueue and dequeue operations in a queue? c)

More information

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

q To develop recursive methods for recursive mathematical functions ( ). Chapter 8 Recursion CS: Java Programming Colorado State University Motivations Suppose you want to find all the files under a directory that contains a particular word. How do you solve this problem? There

More information

CSCS-200 Data Structure and Algorithms. Lecture

CSCS-200 Data Structure and Algorithms. Lecture CSCS-200 Data Structure and Algorithms Lecture-13-14-15 Recursion What is recursion? Sometimes, the best way to solve a problem is by solving a smaller version of the exact same problem first Recursion

More information

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

q To develop recursive methods for recursive mathematical functions ( ). /2/8 Chapter 8 Recursion CS: Java Programming Colorado State University Motivations Suppose you want to find all the files under a directory that contains a particular word. How do you solve this problem?

More information

CS171 Final Practice Exam

CS171 Final Practice Exam CS171 Final Practice Exam Name: You are to honor the Emory Honor Code. This is a closed-book and closed-notes exam. You have 150 minutes to complete this exam. Read each problem carefully, and review your

More information

Building Java Programs

Building Java Programs Building Java Programs Binary Trees reading: 17.1 17.3 2 Trees in computer science TreeMap and TreeSet implementations folders/files on a computer family genealogy; organizational charts AI: decision trees

More information

CE 221 Data Structures and Algorithms

CE 221 Data Structures and Algorithms CE 221 Data Structures and Algorithms Chapter 4: Trees (Binary) Text: Read Weiss, 4.1 4.2 Izmir University of Economics 1 Preliminaries - I (Recursive) Definition: A tree is a collection of nodes. The

More information

Binary Trees

Binary Trees Binary Trees 4-7-2005 Opening Discussion What did we talk about last class? Do you have any code to show? Do you have any questions about the assignment? What is a Tree? You are all familiar with what

More information

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

BRONX COMMUNITY COLLEGE of the City University of New York DEPARTMENT OF MATHEMATICS AND COMPUTER SCIENCE. Sample Final Exam BRONX COMMUNITY COLLEGE of the City University of New York DEPARTMENT OF MATHEMATICS AND COMPUTER SCIENCE CSI33 Sample Final Exam NAME Directions: Solve problems 1 through 5 of Part I and choose 5 of the

More information

Data Structures And Algorithms

Data Structures And Algorithms Data Structures And Algorithms Binary Trees Eng. Anis Nazer First Semester 2017-2018 Definitions Linked lists, arrays, queues, stacks are linear structures not suitable to represent hierarchical data,

More information

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

Data Structure Lecture#10: Binary Trees (Chapter 5) U Kang Seoul National University Data Structure Lecture#10: Binary Trees (Chapter 5) U Kang Seoul National University U Kang (2016) 1 In This Lecture The concept of binary tree, its terms, and its operations Full binary tree theorem Idea

More information

Chapter 15: Recursion

Chapter 15: Recursion Chapter 15: Recursion Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis Chapter Topics Chapter 15 discusses the following main topics: Introduction to Recursion

More information

recursive algorithms 1

recursive algorithms 1 COMP 250 Lecture 11 recursive algorithms 1 Oct. 2, 2017 1 Example 1: Factorial (iterative)! = 1 2 3 1 factorial( n ){ // assume n >= 1 result = 1 for (k = 2; k

More information

Algorithms and Data Structures

Algorithms and Data Structures Lesson 3: trees and visits Luciano Bononi http://www.cs.unibo.it/~bononi/ (slide credits: these slides are a revised version of slides created by Dr. Gabriele D Angelo) International

More information

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

Discussion 2C Notes (Week 8, February 25) TA: Brian Choi Section Webpage: Discussion 2C Notes (Week 8, February 25) TA: Brian Choi (schoi@cs.ucla.edu) Section Webpage: http://www.cs.ucla.edu/~schoi/cs32 Trees Definitions Yet another data structure -- trees. Just like a linked

More information

CS 206 Introduction to Computer Science II

CS 206 Introduction to Computer Science II CS 206 Introduction to Computer Science II 03 / 05 / 2018 Instructor: Michael Eckmann Today s Topics Questions? Comments? binary search trees Finish delete method Discuss run times of various methods Michael

More information

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

CSE 332 Spring 2013: Midterm Exam (closed book, closed notes, no calculators) Name: Email address: Quiz Section: CSE 332 Spring 2013: Midterm Exam (closed book, closed notes, no calculators) Instructions: Read the directions for each question carefully before answering. We will

More information

CSE 2123 Recursion. Jeremy Morris

CSE 2123 Recursion. Jeremy Morris 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

More information

Class 27: Nested Classes and an Introduction to Trees

Class 27: Nested Classes and an Introduction to Trees Introduction to Computation and Problem Solving Class 27: Nested Classes and an Introduction to Trees Prof. Steven R. Lerman and Dr. V. Judson Harward Goals To explain in more detail the different types

More information

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

Recursion CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2011 Recursion CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2011 Recursion A method calling itself Overview A new way of thinking about a problem Divide and conquer A powerful programming

More information

CS171 Final Practice Exam

CS171 Final Practice Exam CS171 Final Practice Exam Name: You are to honor the Emory Honor Code. This is a closed-book and closed-notes exam. You have 150 minutes to complete this exam. Read each problem carefully, and review your

More information

C22a: Problem Solving using Recursion

C22a: Problem Solving using Recursion CISC 3115 TY3 C22a: Problem Solving using Recursion Hui Chen Department of Computer & Information Science CUNY Brooklyn College 11/6/2018 CUNY Brooklyn College 1 Outline Characteristics of recursion Recursion

More information

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

Trees! Ellen Walker! CPSC 201 Data Structures! Hiram College! Trees! Ellen Walker! CPSC 201 Data Structures! Hiram College! ADTʼs Weʼve Studied! Position-oriented ADT! List! Stack! Queue! Value-oriented ADT! Sorted list! All of these are linear! One previous item;

More information

Introduction to Algorithms and Data Structures

Introduction to Algorithms and Data Structures Introduction to Algorithms and Data Structures Lecture 12 - I think that I shall never see.. a data structure lovely as a Binary Tree What is a Binary Tree A binary tree is a a collection of nodes that

More information

Recursion. Chapter 5

Recursion. Chapter 5 Recursion Chapter 5 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn how to write recursive algorithms and methods for searching arrays To learn

More information

Binary Trees. Examples:

Binary Trees. Examples: Binary Trees A tree is a data structure that is made of nodes and pointers, much like a linked list. The difference between them lies in how they are organized: In a linked list each node is connected

More information

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

Recursion. Tracing Method Calls via a Stack. Beyond this lecture... Recursion EECS2030 B: Advanced Object Oriented Programming Fall 2018 CHEN-WEI WANG Recursion: Principle Recursion is useful in expressing solutions to problems that can be recursively defined: Base Cases:

More information

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

Recursion. Overview. Mathematical induction. Hello recursion. Recursion. Example applications. Goal: Compute factorial N! = 1 * 2 * 3... Recursion Recursion Overview A method calling itself A new way of thinking about a problem Divide and conquer A powerful programming paradigm Related to mathematical induction Example applications Factorial

More information

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

Give one example where you might wish to use a three dimensional array CS 110: INTRODUCTION TO COMPUTER SCIENCE SAMPLE TEST 3 TIME ALLOWED: 60 MINUTES Student s Name: MAXIMUM MARK 100 NOTE: Unless otherwise stated, the questions are with reference to the Java Programming

More information

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

Round and round recursion: the good, the bad, the ugly, the hidden Round and round recursion: the good, the bad, the ugly, the hidden ACSE 2006 Talk Troy Vasiga Lecturer, University of Waterloo Director, CCC Outline Recursion defined Real-world examples ("The hidden")

More information

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

R10 SET - 1. Code No: R II B. Tech I Semester, Supplementary Examinations, May www.jwjobs.net R10 SET - 1 II B. Tech I Semester, Supplementary Examinations, May - 2012 (Com. to CSE, IT, ECC ) Time: 3 hours Max Marks: 75 *******-****** 1. a) Which of the given options provides the

More information

Data Structures And Algorithms

Data Structures And Algorithms Data Structures And Algorithms Recursion Eng. Anis Nazer First Semester 2016-2017 Recursion Recursion: to define something in terms of itself Example: factorial n!={ 1 n=0 n (n 1)! n>0 Recursion Example:

More information

Binary Trees, Binary Search Trees

Binary Trees, Binary Search Trees Binary Trees, Binary Search Trees Trees Linear access time of linked lists is prohibitive Does there exist any simple data structure for which the running time of most operations (search, insert, delete)

More information

cs Java: lecture #6

cs Java: lecture #6 cs3101-003 Java: lecture #6 news: homework #5 due today little quiz today it s the last class! please return any textbooks you borrowed from me today s topics: interfaces recursion data structures threads

More information

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

Trees. Dr. Ronaldo Menezes Hugo Serrano Ronaldo Menezes, Florida Tech Trees Dr. Ronaldo Menezes Hugo Serrano (hbarbosafilh2011@my.fit.edu) Introduction to Trees Trees are very common in computer science They come in different variations They are used as data representation

More information

CS 180 Problem Solving and Object Oriented Programming Fall 2011

CS 180 Problem Solving and Object Oriented Programming Fall 2011 CS 180 Problem Solving and Object Oriented Programming Fall 2011 hlp://www.cs.purdue.edu/homes/apm/courses/cs180fall2011/ This Week: Notes for Week : Nov 28- Dec 2, 2011 11/28-30 1. ExcepUons 2. Recursion

More information

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

Binary Tree. Binary tree terminology. Binary tree terminology Definition and Applications of Binary Trees Binary Tree (Chapter 0. Starting Out with C++: From Control structures through Objects, Tony Gaddis) Le Thanh Huong School of Information and Communication Technology Hanoi University of Technology 11.1

More information

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

Figure 18.4 A Unix directory. 02/13/03 Lecture 11 1 Figure 18.4 A Unix directory 02/13/03 Lecture 11 1 Figure 18.7 The Unix directory with file sizes 02/13/03 Lecture 11 2 Figure 18.11 Uses of binary trees: (a) an expression tree and (b) a Huffman coding

More information