Recursion Bryce Boe 2013/11/18 CS24, Fall 2013. Outline Wednesday Recap Lab 7 Iterative Solution Recursion Binary Tree Traversals Lab 7 Recursive Solution.

Slides:



Advertisements
Similar presentations
S. Sudarshan Based partly on material from Fawzi Emad & Chau-Wen Tseng
Advertisements

IKI 10100: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100: Lecture20.
IKI 10100I: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100I: Data.
Binary Trees Chapter 6. Linked Lists Suck By now you realize that the title to this slide is true… By now you realize that the title to this slide is.
Binary Trees, Binary Search Trees CMPS 2133 Spring 2008.
Binary Trees, Binary Search Trees COMP171 Fall 2006.
Trees, Binary Trees, and Binary Search Trees COMP171.
BST Data Structure A BST node contains: A BST contains
CS 240: Data Structures Thursday, August 2nd Trees – Traversals, Representations, Recursion and Helpers.
Binary Search Trees Chapter 7 Objectives
1 BST Trees A binary search tree is a binary tree in which every node satisfies the following: the key of every node in the left subtree is.
1 Joe Meehean.  Important and common problem  Given a collection, determine whether value v is a member  Common variation given a collection of unique.
More Trees COL 106 Amit Kumar and Shweta Agrawal Most slides courtesy : Douglas Wilhelm Harder, MMath, UWaterloo
By : Budi Arifitama Pertemuan ke Objectives Upon completion you will be able to: Create and implement binary search trees Understand the operation.
Properties: -Each node has a value -The left subtree contains only values less than the parent node’s value -The right subtree contains only values greater.
Priority Queues and Heaps Bryce Boe 2013/11/20 CS24, Fall 2013.
Trees, Binary Search Trees, Recursion, Project 2 Bryce Boe 2013/08/01 CS24, Summer 2013 C.
Lecture Objectives  To learn how to use a tree to represent a hierarchical organization of information  To learn how to use recursion to process trees.
Tree. Basic characteristic Top node = root Left and right subtree Node 1 is a parent of node 2,5,6. –Node 2 is a parent of node.
Binary Trees Chapter Definition And Application Of Binary Trees Binary tree: a nonlinear linked list in which each node may point to 0, 1, or two.
CISC220 Fall 2009 James Atlas Lecture 13: Trees. Skip Lists.
1 Trees A tree is a data structure used to represent different kinds of data and help solve a number of algorithmic problems Game trees (i.e., chess ),
Trees, Binary Trees, and Binary Search Trees COMP171.
Binary Search Tree Traversal Methods. How are they different from Binary Trees?  In computer science, a binary tree is a tree data structure in which.
 Trees Data Structures Trees Data Structures  Trees Trees  Binary Search Trees Binary Search Trees  Binary Tree Implementation Binary Tree Implementation.
Lec 15 Oct 18 Binary Search Trees (Chapter 5 of text)
Preview  Graph  Tree Binary Tree Binary Search Tree Binary Search Tree Property Binary Search Tree functions  In-order walk  Pre-order walk  Post-order.
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Modified for use at Midwestern State University Chapter.
+ David Kauchak cs312 Review. + Midterm Will be posted online this afternoon You will have 2 hours to take it watch your time! if you get stuck on a problem,
CSE 3358 NOTE SET 10 Data Structures and Algorithms.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 1 Chapter 19 Binary Search Trees.
1 Chapter 7 Objectives Upon completion you will be able to: Create and implement binary search trees Understand the operation of the binary search tree.
CMSC 341 Introduction to Trees. 2/21/20062 Tree ADT Tree definition –A tree is a set of nodes which may be empty –If not empty, then there is a distinguished.
1/14/20161 BST Operations Data Structures Ananda Gunawardena.
Trees 3 The Binary Search Tree Section 4.3. Binary Search Tree Also known as Totally Ordered Tree Definition: A binary tree B is called a binary search.
ADT Binary Search Tree Ellen Walker CPSC 201 Data Structures Hiram College.
Binary Search Trees (BST)
Copyright © 2012 Pearson Education, Inc. Chapter 20: Binary Trees.
COSC 2P03 Week 21 Tree Traversals – reminder Breadth-first traversal: starting from root, visit all nodes on each level in turn, from left to right Depth-first.
1 Trees General Trees  Nonrecursive definition: a tree consists of a set of nodes and a set of directed edges that connect pairs of nodes.
Binary Tree Implementation. Binary Search Trees (BST) Nodes in Left subtree has smaller values Nodes in right subtree has bigger values.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 20: Binary Trees.
1 Joe Meehean. A A B B D D I I C C E E X X A A B B D D I I C C E E X X  Terminology each circle is a node pointers are edges topmost node is the root.
CMSC 202, Version 5/02 1 Trees. CMSC 202, Version 5/02 2 Tree Basics 1.A tree is a set of nodes. 2.A tree may be empty (i.e., contain no nodes). 3.If.
More Binary Search Trees, Project 2 Bryce Boe 2013/08/06 CS24, Summer 2013 C.
1 Trees General Trees  Nonrecursive definition: a tree consists of a set of nodes and a set of directed edges that connect pairs of nodes.
Trees By JJ Shepherd. Introduction Last time we discussed searching and sorting in a more efficient way Divide and Conquer – Binary Search – Merge Sort.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 20: Binary Trees.
1 Binary Search Trees. 2 Binary Search Trees Binary Search Trees The Binary Search Tree (BST) Search, Insertion and Traversal of BST Removal of nodes.
1 Trees 3: The Binary Search Tree Reading: Sections 4.3 and 4.6.
Binary Search Trees Chapter 7 Objectives
BST Trees
UNIT III TREES.
Week 6 - Wednesday CS221.
Binary Search Tree (BST)
Lecture 22 Binary Search Trees Chapter 10 of textbook
ITEC 2620M Introduction to Data Structures
Binary Trees, Binary Search Trees
Chapter 20: Binary Trees.
Map interface Empty() - return true if the map is empty; else return false Size() - return the number of elements in the map Find(key) - if there is an.
Chapter 21: Binary Trees.
Lec 12 March 9, 11 Mid-term # 1 (March 21?)
Find in a linked list? first last 7  4  3  8 NULL
CMSC 341 Binary Search Trees.
Lecture 12 CS203 1.
Binary Trees, Binary Search Trees
CMSC 341 Binary Search Trees.
CSC 143 Binary Search Trees.
Non-Linear data structures
Binary Trees, Binary Search Trees
Presentation transcript:

Recursion Bryce Boe 2013/11/18 CS24, Fall 2013

Outline Wednesday Recap Lab 7 Iterative Solution Recursion Binary Tree Traversals Lab 7 Recursive Solution Merge Sort BST Remove

WEDNESDAY RECAP

What is the depth of G? 3 3

What is the height of B? 1 1

What is the height of the tree? 3 3

Is the tree balanced? No

LAB 7 SOLUTION

RECURSION

What is recursion? The process of solving a problem by dividing it into similar subproblems Examples – Factorial: 5! = 5 * 4! = 5 * 4 * 3! – Length of linked list: L(node) = 1 + L(node->next) – Fibonacci Numbers: F(N) = F(n-1) + F(n-2)

Factorial Base Case: – F(1) = 1 General Case – F(n) = n * F(n-1)

Factorial int factorial(n) { if (n < 1) throw 1; // Error condition else if (n == 1) // Base Case return 1; else // General Case return n * factorial(n – 1); }

Linked List Length Base Case: – Length(last node) = 1 General Case: – Length(node) = 1 + Length(node->next);

Linked List Length (option 1) int length(Node *n) { if (n == NULL) // Base Case return 0; else // General Case return 1 + length(n->next); }

Linked List Length (option 2) int length(Node *n) { if (n == NULL) throw 1; // Error condition else if (n->next == NULL) // Base Case return 1; else // General Case return 1 + length(n->next); } What is the size of the simplified activation record? How much space is required for a list with 8 items?

Fibonacci Numbers Base Cases: – F(0) = 0 – F(1) = 1 General Case: – F(n) = F(n-1) + F(n-2)

Recursion and the Stack Segment main calls Factorial(3) main Factorial(3) Factorial(2) Factorial(1)

Recursion question How many activation records are created when calling Fibonacci(0)? Fibonacci(1)? Fibonacci(2)? Fibonacci(3)? Fibonacci(4)? Fibonacci(5)?

BINARY TREE TRAVERSALS

Depth-First Tree Traversals Can be done iteratively (with a stack) or recursively Pre-order – Process the node, recurse on left subtree, recurse on right subtree In-order – Recurse on the left subtree, process the node, recurse on the right subtree Post-order – Recurse on the left subtree, recurse on the right subtree, process the node

Pre-Order Traversal A -> B - > D -> E -> C -> F -> G -> H

In-Order Traversal D -> B -> E -> A -> C -> G -> F -> H

Post-Order Traversal D -> E -> B -> G -> H -> F -> C -> A

Breadth-first Traversal Cannot be done recursively Done iteratively with the help of a queue – You did this in lab 7

Breadth-first (queue lhs before rhs) A -> B -> C -> D -> E -> F -> G -> H

Question Which of the traversals will output a sorted version of a binary search tree? When should you use recursion / iteration? – Most importantly: use what you’re comfortable with – With recursion be careful of stack depth (O(log(n)) memory is okay, O(n) is probably not) CHALLENGE: – Implement the three depth-first traversals iteratively

LAB 7 RECURSIVE SOLUTION

Lab 7 Recursive ~BST template void bst_destruct(BinaryNode *node) { if (node != NULL) { bst_destruct(node->get_rhs()); bst_destruct(node->get_lhs()); delete node; } template BST ::~BST() { bst_destruct(root); } What traversal order is this? How much memory is required?

Lab 7 Recursive insert template bool BST ::insert(T item) { try { root = bst_insert(root, item); return true; } catch (int e) { return false; }

Lab 7 Recursive insert template BinaryNode *bst_insert(BinaryNode *node, T item) { if (node == NULL) return new BinaryNode (item, NULL, NULL); else if (item == node->get_data()) throw 1; else if (item get_data()) node->set_lhs(bst_insert(node->get_lhs(), item)); else node->set_rhs(bst_insert(node->get_rhs(), item)); return node; } How much memory is required?

Save space by using const references where appropriate template BinaryNode *bst_insert(BinaryNode *node, const T &item) { if (node == NULL) return new BinaryNode (item, NULL, NULL); else if (item == node->get_data()) throw 1; else if (item get_data()) node->set_lhs(bst_insert(node->get_lhs(), item)); else node->set_rhs(bst_insert(node->get_rhs(), item)); return node; }

MERGE SORT

O(nlog(n)) Sort Algorithms Merge Sort – Divide the problem in half until you have 1 or 2 items and put them in order – Merge the two sorted halves T(n) = 2T(n/2) + O(n) === O(n*log(n)) – (masters theorem)

Coding Hint What’s wrong with the following? int *tmp = new int[10]; tmp = some_function(); results in a memory leak

BST REMOVAL

Recall A binary search tree is a tree with the property that the value of all descendants of a node’s left subtree are smaller, and the value of all descendants of a node’s right subtree are larger

BST Example

BST Remove If the node has no children simply remove it If the node has a single child, update its parent pointer to point to its child and remove the node

Removing a node with two children Replace the value of the node with the largest value in its left-subtree (right-most descendant on the left hand side) – Note you could use the smallest value in the right- subtree (but for consistency please don’t) Then repeat the remove procedure to remove the node whose value was used in the replacement

Removing a node with two children