Chapfaculty.cse.tamu.edu/slupoli/notes/Java/RecursionTree… · Web viewParts of a recursive...

34
Recursion & Intro to Trees Theory of Recursion Functions that call themselves Used to greatly reduce code Save space and time if done right Uses system stack to maintain call order When NOT to use Recursion when using large arrays or datatypes when using global variables Applications of Recursion Theoretical / Mathematical Recursion Parts of a recursive function in JAVA Other mathematical equations using recursion “Robot” Recursion “Virus” Recursion 1

Transcript of Chapfaculty.cse.tamu.edu/slupoli/notes/Java/RecursionTree… · Web viewParts of a recursive...

Page 1: Chapfaculty.cse.tamu.edu/slupoli/notes/Java/RecursionTree… · Web viewParts of a recursive function in JAVA Other mathematical equations using recursion “Robot” Recursion “Virus”

Recursion & Intro to Trees

Theory of Recursion Functions that call themselves Used to greatly reduce code Save space and time if done right Uses system stack to maintain call order

When NOT to use Recursion when using large arrays or datatypes when using global variables

Applications of Recursion Theoretical / Mathematical Recursion Parts of a recursive function in JAVA Other mathematical equations using recursion “Robot” Recursion “Virus” Recursion

1

Page 2: Chapfaculty.cse.tamu.edu/slupoli/notes/Java/RecursionTree… · Web viewParts of a recursive function in JAVA Other mathematical equations using recursion “Robot” Recursion “Virus”

Mathematical RecursionWork on these on another sheet of paperf(10) = ??? (I’ll do this one)

f(x) = { f(x-3)+2 x>1x + 3

F(10) = F(7)+2“call” stack “value” stack

f(9) = ???

f(x) = { 3 * f(x-1) x>= 25

f(9) = ???

f(x) = { 34*f(x-1) x >= 2

f(7) = ???

f(x) = { f(x-3)+2 x>1x + 3

F(10) = ??? How about f(5)???TWO CALL RECURSIVE FUNCTION!!!

f(x) = { x+5 x<=0f(x-1)*3 + f(x-2)*2

f(8,5) = ???

2

Page 3: Chapfaculty.cse.tamu.edu/slupoli/notes/Java/RecursionTree… · Web viewParts of a recursive function in JAVA Other mathematical equations using recursion “Robot” Recursion “Virus”

f(x,y) = { 6 x<=0f(x-2, y –1) + x*y

Parts of a Recursive Function

int Factorial(int n) {

if (n==0) // base case when n = 0{ return 1; }

//returnselse

{ return n * Factorial(n-1);} // tail recursion – last possible // statement is a recursive call

}

3

Page 4: Chapfaculty.cse.tamu.edu/slupoli/notes/Java/RecursionTree… · Web viewParts of a recursive function in JAVA Other mathematical equations using recursion “Robot” Recursion “Virus”

Permutationsgives all possible combinations of strings (or numbers)

Example of a Permutation FunctionCode Example

void main( ){

Permutations("fat", 3);}

void Permutations (string x, int n){

if(n <= 1) // base case{ cout << x << endl; }else{

for(int i = 0; i < n; i++){Swap(x[i], x[n-1]);Permutations(x, n-1);Swap(x[n-1], x[i]);}

}}

Fibonacci A numerical value where the first two terms are equal to one, with each

consecutive number equal to the sum of the two proceeding numbers

1, 1, 2, 3, 5, 8, 13, …

Example of a Fibonacci FunctionCode Example

public static void main(String args[]){

for(int i = 0; i < 10; i++){ System.out.println( Fibonacci(i)); }

}

int Fibonacci (int n){ if(n <= 2) // base case { return 1; } else { return Fibonacci(n-1) + Fibonacci(n-2); }}

4

Page 5: Chapfaculty.cse.tamu.edu/slupoli/notes/Java/RecursionTree… · Web viewParts of a recursive function in JAVA Other mathematical equations using recursion “Robot” Recursion “Virus”

Virus or “Fill will Color” Recursion Used in:

o virus spread models (Movie: Outbreak)o “Fill” option in Paint

1st time through 2nd time through↑

↑← X →↑← X X X →

←↓ X ↓→↓

void virus(char [][] matrix, int row_pos, int col_pos){if(matrix[row_pos][col_pos] = = ‘X’) // then already INFECTED!!!

{ return; }else{

matrix[row_pos][col_pos] = ‘X’; // INFECT spotvirus(matrix, row_pos+1, col_pos); // go infect DOWN spot of current positionvirus(matrix, row_pos-1, col_pos); // go infect UP spot of current positionvirus(matrix, row_pos, col_pos+1); // go infect RIGHT spot of current positionvirus(matrix, row_pos, col_pos-1); // go infect LEFT of current position

}

5

Page 6: Chapfaculty.cse.tamu.edu/slupoli/notes/Java/RecursionTree… · Web viewParts of a recursive function in JAVA Other mathematical equations using recursion “Robot” Recursion “Virus”

Robot Recursion much as the same idea of virus except you mark where you have been you look for a wall or a spot you have been before, BEFORE you move

char maze[5][11];N↑

W E↓S

RobotMove(maze, 4, 0); // original START spot

Pseudocode for RobotMove(char [][] maze, int row_pos, int col_pos)

if(maze[row_pos][col_pos] == “Exit”) // FOUND THE EXIT!!{ cout << "FOUND THE EXIT!!!" << endl; }if(maze[row_pos][col_pos] == '+') // then already been here!!!{ return; }else{

maze[row_pos][col_pos] = '+'; // mark spot since we are here

if(((North != 'X') && (row_pos-1 >= 0)) && (North != '+')) //Look North// go move UP spot of current position

if(((South != 'X') && (row_pos+1 <= 4)) && (South != '+')) //Look South// go move DOWN spot of current position

if(((East != 'X') && (col_pos+1 <= 4)) && (East != '+')) //Look East// go move RIGHT spot of current position

if(((West != 'X') && (col_pos-1 >= 0)) && (West != '+')) //Look West// go move LEFT of current position

}

6

Exit

start

Page 7: Chapfaculty.cse.tamu.edu/slupoli/notes/Java/RecursionTree… · Web viewParts of a recursive function in JAVA Other mathematical equations using recursion “Robot” Recursion “Virus”

Intro. to TreesWhat is a tree??

LINK/EDGE

Element/NODE

Other parts of a treeOther parts of a tree

root internal nodes leafs

path descendants

Length of a tree

A

K QFZ

AK Q

FZ

AK Q

FZ

AK Q

FZ

AK Q

FZ

AK Q

FZ

7

Page 8: Chapfaculty.cse.tamu.edu/slupoli/notes/Java/RecursionTree… · Web viewParts of a recursive function in JAVA Other mathematical equations using recursion “Robot” Recursion “Virus”

Determining the Length of a TreeHeight Level

1 02 13 2

Relationships of a tree - Part 1“A” – no parents“A” - 2 children “K” and “Q”

“K” – Parent is “A” “Q” – Parent is “A”“K” - 1 child “Z”

“Z” – Parent is “K”“Z” – no children Z’s ancestors are “K” and “A”Other Info on Trees

Trees are SHALLOW – they can hold many nodes with very few levels A height of 21 can hold 1048575 nodes

K Q

Z

A

AK Q

FZ

8

Page 9: Chapfaculty.cse.tamu.edu/slupoli/notes/Java/RecursionTree… · Web viewParts of a recursive function in JAVA Other mathematical equations using recursion “Robot” Recursion “Virus”

2height -1 = How many TOTAL nodes can he held by this tree

Tree is inherently recursive structure, because each node in a tree can itself be viewed as the root of a smaller tree.

Types of Trees also called classification Binary

o has only AT MOST 2 childreno used in Binary Searcho used in Tree Traversals (covered later)o built (usually) in order

Regular Binary // ex. Which-Way bookso has only 2 childreno may have a link back up to the parento may be built OUT of ordero or data inside each node has a patterno each like (left and right) is traveled depending on choice

yes = left link no = right link

Regular Treeo may have MANY links to MANY kids!!!

B- Trees o Tailored toward applications where tree doesn’t fit in memoryo operations much faster than disk accesseso want to limit levels of tree (because each new level requires a disk access)o keep root and top level in memoryo An Alternative to BSTso Up until now we assumed that each node in a BST stored the data.o What about having the data stored only in the leaves?o The internal nodes just guide our search to the leaf which contains the data

we want.o We’ll restrict this discussion of such trees to those in which all leaves are

at the same level.9

Page 10: Chapfaculty.cse.tamu.edu/slupoli/notes/Java/RecursionTree… · Web viewParts of a recursive function in JAVA Other mathematical equations using recursion “Robot” Recursion “Virus”

A BST with data stored in the leaves

Red-Black Treeso A red-black tree is a binary search tree in which:

Every node is colored either Red or Black. Each NULL pointer is considered to be a Black “node”. If a node is Red, then both of its children are Black. Every path from a node to a NULL contains the same number of

Black nodes. By convention, the root is Black

o The black-height of a node, X, in a red-black tree is the number of Black nodes on any path to a NULL, not counting X.

10

Page 11: Chapfaculty.cse.tamu.edu/slupoli/notes/Java/RecursionTree… · Web viewParts of a recursive function in JAVA Other mathematical equations using recursion “Robot” Recursion “Virus”

Red-Black Tree Example

o A Red-Black Tree with NULLs showno Black-Height of the tree (the root) = 3

Black-Height of node “X” = 2 Splay Trees

o Problems with BSTso Because the shape of a BST is determined by the order that data is

inserted, we run the risk of trees that are essentially lists

Splay Tree Example

2112

20

15

32

24 37

40

55

56

77

11

Page 12: Chapfaculty.cse.tamu.edu/slupoli/notes/Java/RecursionTree… · Web viewParts of a recursive function in JAVA Other mathematical equations using recursion “Robot” Recursion “Virus”

is a self-adjusting binary search tree with the special feature that recently accessed elements are quick to access again.

o The basic idea of the splay tree is that every time a node is accessed, it is pushed to the root by a series of tree rotations. This series of tree rotations is knowing as “splaying”.

12

Page 13: Chapfaculty.cse.tamu.edu/slupoli/notes/Java/RecursionTree… · Web viewParts of a recursive function in JAVA Other mathematical equations using recursion “Robot” Recursion “Virus”

Representing a Tree There are two ways to represent trees

o Linked Lists use links to connect to the other nodes in the tree

o Array much like Heap Sort algorithm

Representing a TreeLinked List

“Helter Skelter”

Array

[0] [1] [2] [3] [4] [5]

[6]

7 5 1 2 3 6

// it is possible to have an empty element

// draw indices OVER middle tree

DATAparent->link

left->linkright->link

71

13

Page 14: Chapfaculty.cse.tamu.edu/slupoli/notes/Java/RecursionTree… · Web viewParts of a recursive function in JAVA Other mathematical equations using recursion “Robot” Recursion “Virus”

Draw the tree from the given info.5 9 7 1 6 3 4 8 0

Array->Tree

9 5 6 7 1 2 6 8 4Tree

ArrayTree

23 6

55 1

3 6 7

14

Page 15: Chapfaculty.cse.tamu.edu/slupoli/notes/Java/RecursionTree… · Web viewParts of a recursive function in JAVA Other mathematical equations using recursion “Robot” Recursion “Virus”

Binary Tree Traversals the process of “visiting” or performing some operations on, each node

of a tree is called TREE TRAVERSAL a traversal is to process each node ONCE There are 3 commonly used to traversals

o preordero inordero postorder o they differ in the sequence in which the nodes are visited

PREORDER/PREFIX1. process root first2. if (left child present, and not visited already) move to left, restart

with Step 1 at new node3. if (right child present, and not visited already) move to right, restart

with Step 1 at new node4. Else, go back up to parent, and start at step 3

overall, the algorithm reaches the root first INORDER/INFIX

1. if (left child present, and not visited already) move to left, restart with Step 1 at new node

2. process root3. if (right child present, and not visited already) move to right, restart

with Step 1 at new node4. Else go back up to parent, and start at step 2

POSTORDER/POSTFIX1. if (left child present, and not visited already) move to left, restart

with Step 1 at new node2. if (right child present, and not visited already) move to right, restart

with Step 1 at new node3. Else process root, go back to parent, and start at step 2

overall, the algorithm reaches the root LAST

15

Page 16: Chapfaculty.cse.tamu.edu/slupoli/notes/Java/RecursionTree… · Web viewParts of a recursive function in JAVA Other mathematical equations using recursion “Robot” Recursion “Virus”

Practicing Tree Traversals Guarantees that we will visit EACH node at least once

o No man left behind!!! Always start at the root

Inorder

(L, P, R)

// I will do, you do next 5

Preorder

(P, L, R)Postorder

(L, R, P)Inorder

Preorder

Postorder

Inorder ORDERED TREE!!!

How was Inorder Helpful??Preorder

How was PreOrder Helpful??Postorder

How was PostOrder Helpful??

56 7

12 98 0 2

6

6 7

91 5

2

0 7

14 85

616

Page 17: Chapfaculty.cse.tamu.edu/slupoli/notes/Java/RecursionTree… · Web viewParts of a recursive function in JAVA Other mathematical equations using recursion “Robot” Recursion “Virus”

Hints on Building Trees UNLIKE LINKED LISTS, YOU MUST HAVE A GAME PLAN!! The FIRST node is always the simplest since there are no other nodes The rest of the nodes placed, must be traveled to the precise location

needed, then placed Just like Linked Lists, remember to assign your links

o most will be set to NULL (left and right)o link from Parent to new nodeo link from new node to Parent

The Game plans “Helter Skelter”

o Place them ANYWHERE you want BST

o Order by some type of logic A < Z 0 < 100

o Also considers the ORDER items was received (and placed) in tree Full

o Fill each LEVEL one at a time

Creating a Binary Search Tree in a Binary Search Tree

o items to the left are smaller in valueo items to the right are larger in value

Simple Binary Tree Complex Binary Tree

46 2

23 97 5 8

17

Page 18: Chapfaculty.cse.tamu.edu/slupoli/notes/Java/RecursionTree… · Web viewParts of a recursive function in JAVA Other mathematical equations using recursion “Robot” Recursion “Virus”

18

Page 19: Chapfaculty.cse.tamu.edu/slupoli/notes/Java/RecursionTree… · Web viewParts of a recursive function in JAVA Other mathematical equations using recursion “Robot” Recursion “Virus”

Adding a Node to a Binary tree remember game plan!!

Drawing what adding should doFirst Node (M) Adding another (T) Adding another (Z)

Adding another (B) Adding another (F) Adding another (A)

Placing a Node// place the nodes in a binary search tree in the order given

8,1,0,9,6,5,3,7,4

5,9,1,8,0,6,7,3,4

8,0,1,6,9,3,4,7,5// what TRAVERSAL algorithm will display ALL of these trees in numerical order??

BST- Binary Search Trees19

Page 20: Chapfaculty.cse.tamu.edu/slupoli/notes/Java/RecursionTree… · Web viewParts of a recursive function in JAVA Other mathematical equations using recursion “Robot” Recursion “Virus”

use divide and conquer methods for searching, deleting, inserting, etc… what makes a binary tree

o nodes have no more than 2 children o all nodes have data placed insideo for any node, the element in the node is larger than all elements in

the node’s right subtree, and smaller than all elements in this node’s left subtree

o smallest and largest elements in a tree are easy to find for the smallest, keep going right, until no longer possible, or

until left is the only option for the largest, keep going left, until no longer possible, or

until right is the only optiono 2 types of Binary Trees

Full Binary Tree – EVERY leaf has the same depth, and every non-leaf has 2 children

Complete Binary Tree – Take a FULL binary tree, and start adding new leaves at a new depth from left to right. All of the new leaves are at the same depth

we will use linked lists for all functions instead of arrayso easy to createo easy to locate a targeto easy to add/insert, or deletes a node

step by step psuedocode to find data in a BST1. determine what the target is2. start at the top of the tree, the “root”3. compare target to the root

a. if target == root, target has been foundb. if target < root, left child becomes the root (repeat step 3)c. if target > root, right child becomes the root (repeat step 3)

number of times we check the root will always be less that the height of the tree

20

Page 21: Chapfaculty.cse.tamu.edu/slupoli/notes/Java/RecursionTree… · Web viewParts of a recursive function in JAVA Other mathematical equations using recursion “Robot” Recursion “Virus”

Simple Binary Tree Search Exampletarget is red target is red

target is red NEW target is red

KQ A

1

KQ A

NE MP Z S

KQ A

NE MP Z S

21

Page 22: Chapfaculty.cse.tamu.edu/slupoli/notes/Java/RecursionTree… · Web viewParts of a recursive function in JAVA Other mathematical equations using recursion “Robot” Recursion “Virus”

A look at the BinarySearchTree code Yes, we are STILL in trees, but using Binary theory to add and find

nodes in a tree (game plan) Notice looks A LOT like Linked Lists

o why we cover it FIRST!!! Look at FIRST “insert” function

o notice it looks at name in order to PLACE or MOVE either to left or right

o notice in a loop since we may have to travel for a while to get to our correct spot to add

Let’s Id a few important features for the code!!

22

Page 23: Chapfaculty.cse.tamu.edu/slupoli/notes/Java/RecursionTree… · Web viewParts of a recursive function in JAVA Other mathematical equations using recursion “Robot” Recursion “Virus”

Traveling through a Binary tree let use the infix algorithm

Drawing what traveling should do

CodingPsuedocode Code

KQ A

NE MP Z S

23

Page 24: Chapfaculty.cse.tamu.edu/slupoli/notes/Java/RecursionTree… · Web viewParts of a recursive function in JAVA Other mathematical equations using recursion “Robot” Recursion “Virus”

Other functions that would be worth while Search function

o find a person within that treeo use the binary search method

(after target determined) define middle is middle == target go left or right

Remove functiono much like the reheapify functiono find our target

use the search algorithm aboveo restructure the tree

THIS CAN BE COMPLICATED!!

24

Page 25: Chapfaculty.cse.tamu.edu/slupoli/notes/Java/RecursionTree… · Web viewParts of a recursive function in JAVA Other mathematical equations using recursion “Robot” Recursion “Virus”

FYI - Translating a Equation into JAVA Code

1. Look for base case, and set into a IF statement 2. “else” the rest that do not have condition 3. code for both calls

f(x-3)+2 x>1 f(x) =

x + 3

Translated to:

int f(int x){

if(x > 1){ return f(x-3) + 2; }else{ return x + 3; }

}

F(9) = ?F(15) = ?

Homework:

Translate each mathematical equation into JAVA Code

25