department of computer and information science, school of science, iupui

18
Dale Robert Department of Computer and Information Science, School of Science, IUPUI CSCI 240 Recursion and Trees Dale Roberts, Lecturer Dale Roberts, Lecturer IUPUI IUPUI [email protected] [email protected]

Upload: brett-odonnell

Post on 13-Mar-2016

15 views

Category:

Documents


0 download

DESCRIPTION

Department of Computer and Information Science, School of Science, IUPUI. CSCI 240. Recursion and Trees. Dale Roberts, Lecturer IUPUI [email protected]. A. B. G. C. D. E. F. I. M. H. J. L. N. K. Q. P. Trees. Definitions - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Department of Computer and Information Science, School of Science, IUPUI

Dale Roberts

Department of Computer and Information Science,School of Science, IUPUI

CSCI 240

Recursion and Trees

Dale Roberts, LecturerDale Roberts, [email protected]@cs.iupui.edu

Page 2: Department of Computer and Information Science, School of Science, IUPUI

Dale Roberts

TreesTreesDefinitionsDefinitions

TreeTree: A tree is a collection of nodes. If : A tree is a collection of nodes. If the collection is not empty, it must consist the collection is not empty, it must consist of a unique of a unique rootroot node, node, r, r, and zero or more and zero or more nonempty subtrees nonempty subtrees TT11, T, T22,…, T,…, Tkk, with roots , with roots connected by a direct connected by a direct edgeedge from from rrFor a tree of For a tree of NN nodes, there must be nodes, there must be N-1N-1 edges.edges.A node with no child is called a leaf node; A node with no child is called a leaf node; nodes with the same parents are siblings.nodes with the same parents are siblings.

A

EC D GF

IH

B

MLKJ N

P Q

• Path: a path from node nPath: a path from node n11 to n to nkk is a sequence of nodes n is a sequence of nodes n11, n, n22, …, n, …, nkk such that such that nnii is the parent of n is the parent of ni+1i+1 (1 (1 ii k); The no. of edges in the path is call the k); The no. of edges in the path is call the length of the path; A length 0 path is a path from a node to itself. There is a length of the path; A length 0 path is a path from a node to itself. There is a unique path from root to any node nunique path from root to any node nii; The length of this path is called the ; The length of this path is called the depth of ndepth of nii; thus, the root is a depth 0 node.; thus, the root is a depth 0 node.

• The height of a node nThe height of a node nii is the length of the longest path from n is the length of the longest path from nii to a leaf node, to a leaf node, thus, the height of a leaf node is 0.thus, the height of a leaf node is 0.

• The height of a tree is the height of its root node. The depth of a tree is the The height of a tree is the height of its root node. The depth of a tree is the depth of the deepest leaf node, which is the same as the height of the tree.depth of the deepest leaf node, which is the same as the height of the tree.

Page 3: Department of Computer and Information Science, School of Science, IUPUI

Dale Roberts

TreesTreesHeight – deepest level, Height – deepest level, not including root.not including root.Leaf nodes – have no Leaf nodes – have no childrenchildrenInterior Notes – have at Interior Notes – have at least one childleast one childDegree of a node – Degree of a node – Number of childrenNumber of childrenIn a binary tree, interior In a binary tree, interior nodes have degree 1 or 2.nodes have degree 1 or 2.

A

B C D

F H IG

L

JE

K M

root

subtrees

leaf nodes

child of Aparent of G,H,I and J

degree = 4

heig

ht o

f tre

e is

3

A

B C D

F H IG

L

JE

K M

root

subtrees

leaf nodes

child of Aparent of G,H,I and J

degree = 4

heig

ht o

f tre

e is

3

Page 4: Department of Computer and Information Science, School of Science, IUPUI

Dale Roberts

•Binary trees– Definition: A binary tree is a tree in which no nodes can have more

than two children. (That is, the degree of interior nodes is restricted to 1 or 2.)

– The root node is the first node in a tree. – Each link in the root node refers to a child– A node with no children is called a leaf node– Total number of nodes in a full binary tree of height k is 2k-1

Binary TreesBinary Trees

left child right child

root

left child right child

root

Page 5: Department of Computer and Information Science, School of Science, IUPUI

Dale Roberts

Array implementation of binary treeArray implementation of binary treeWe can embed the nodes of a binary tree into a one-dimensional array We can embed the nodes of a binary tree into a one-dimensional array

by defining a relationship between the position of each parent node by defining a relationship between the position of each parent node and the position of its children. and the position of its children.

1. left_child of node i is 2*i 1. left_child of node i is 2*i 2. right_child of node i is 2*i+1 2. right_child of node i is 2*i+1 3. parent of node i is i/2 (integer division)3. parent of node i is i/2 (integer division)How much space is required for the array to represent a tree of depth How much space is required for the array to represent a tree of depth

d?d? 2d+1 – 1 (must assume full tree)

Page 6: Department of Computer and Information Science, School of Science, IUPUI

Dale Roberts

Dynamic Implementation of Binary TreeDynamic Implementation of Binary TreeA dynamic implementation of a

binary tree uses space proportional to the actual number of nodes used. Not the size of the full tree.

Struct BinaryNode {data_type element;BinaryNode left;BinaryNode right;

}

mar

apr may

jul

feb oct

dec jun nov

sep

null

null

null null

nullnull

null

nullnull nulljan

null

aug

null null

mar

apr may

jul

feb oct

dec jun nov

sep

null

null

null null

nullnull

null

nullnull nulljan

null

aug

null null

data

left-childpointer

right-childpointer

data

left-childpointer

right-childpointer

Page 7: Department of Computer and Information Science, School of Science, IUPUI

Dale Roberts

Binary Search Tree (BST)Binary Search Tree (BST)Binary search tree (BST)Binary search tree (BST)

Values in left subtree less than parent Values in left subtree less than parent Values in right subtree greater than parentValues in right subtree greater than parentFacilitates duplicate eliminationFacilitates duplicate eliminationFast searches - for a balanced tree, maximum of logFast searches - for a balanced tree, maximum of log22(n) comparisons(n) comparisons

ExampleExample: Construct an Binary Search Tree (BST) for the data: Construct an Binary Search Tree (BST) for the data555555 501501 701701 358358 513513 561561 797797 345345 490490 724724

Array Implementation:Array Implementation:

47

25 77

11 43 65 93

68 7 17 31 44

555555

501

555

501 701

555

501 701

358

555

501 701

358 513

555

501 701

358 513 561

555

501 701

358 513 561 797

555

501 701

358 513 561 797

345 490 345

555

501 701

358 513 561 797

490 724

555 501 701 358 513 561 797 345 490 724

Page 8: Department of Computer and Information Science, School of Science, IUPUI

Dale Roberts

Tree TraversalsTree TraversalsTree traversals:Tree traversals:

In-order traversal In-order traversal –– prints the node values in ascending prints the node values in ascending order (LNR)order (LNR)

1. Traverse the left sub-tree with an in-order traversal1. Traverse the left sub-tree with an in-order traversal2. Process the value in the node (i.e., print the node value)2. Process the value in the node (i.e., print the node value)3. Traverse the right sub-tree with an in-order traversal3. Traverse the right sub-tree with an in-order traversal

Pre-order traversal (NLR)Pre-order traversal (NLR)1. Process the value in the node1. Process the value in the node2. Traverse the left sub-tree with a preorder traversal2. Traverse the left sub-tree with a preorder traversal3. Traverse the right sub-tree with a preorder traversal3. Traverse the right sub-tree with a preorder traversal

Post-order traversal (LRN)Post-order traversal (LRN)1. Traverse the left sub-tree with a post-order traversal1. Traverse the left sub-tree with a post-order traversal2. Traverse the right sub-tree with a post-order traversal2. Traverse the right sub-tree with a post-order traversal3. Process the value in the node3. Process the value in the node

Page 9: Department of Computer and Information Science, School of Science, IUPUI

Dale Roberts

A simple definition of recursionA simple definition of recursionRecursion simply means a function that calls Recursion simply means a function that calls itself.itself.The conditions that cause a function to call The conditions that cause a function to call itself again are called the itself again are called the recursive case.recursive case.In order to keep the recursion from going on In order to keep the recursion from going on forever, you must make sure you hit a forever, you must make sure you hit a termination condition called the termination condition called the base casebase case..The number of nested invocations is called the The number of nested invocations is called the depth of recursion.depth of recursion.Function may call itself Function may call itself directlydirectly or or indirectlyindirectly. . (All of our examples are direct.)(All of our examples are direct.)

Page 10: Department of Computer and Information Science, School of Science, IUPUI

Dale Roberts

Tree Traversal is “Naturally” recursiveTree Traversal is “Naturally” recursiveNaturally recursive because:Naturally recursive because:

1.1. Subgraphs are similar in character to the original Subgraphs are similar in character to the original graph.graph.

2.2. Subgraphs are smaller.Subgraphs are smaller.3.3. Guaranteed to eventually hit a leaf (acyclic is assumed)Guaranteed to eventually hit a leaf (acyclic is assumed)

Obeys fundamental rules of recursionObeys fundamental rules of recursion1.) Base cases1.) Base cases2.) Making progress through recursion2.) Making progress through recursion3.) Design rule: assuming all recursive call work (details hidden)3.) Design rule: assuming all recursive call work (details hidden)4.) Compound interest rule: do not duplicate recursive calls4.) Compound interest rule: do not duplicate recursive callsAlways specify the base case; otherwise, indefinite recursive will occur Always specify the base case; otherwise, indefinite recursive will occur

and cause “and cause “stack-overflowstack-overflow” error.” error.

Page 11: Department of Computer and Information Science, School of Science, IUPUI

Dale Roberts

Sample recursive programsSample recursive programsIn-order: (LNR)In-order: (LNR)void inorder(tree_pointer ptr)void inorder(tree_pointer ptr){{ if (ptr) if (ptr) {{ inorder(ptr->left_child);inorder(ptr->left_child); printf(“%d”, ptr->data);printf(“%d”, ptr->data); inorder(ptr->right_child);inorder(ptr->right_child); }}}}Pre-order: (NLR)Pre-order: (NLR)void preorder(tree_pointer ptr)void preorder(tree_pointer ptr){{ if (ptr) if (ptr) {{ printf(“%d”, ptr->data);printf(“%d”, ptr->data); preorder(ptr->left_child);preorder(ptr->left_child); preorder(ptr->right_child);preorder(ptr->right_child); }}}}

Post-order: (LRN)Post-order: (LRN)void postorder(tree_pointer ptr)void postorder(tree_pointer ptr){{ if (ptr) if (ptr) {{ postorder(ptr->left_child);postorder(ptr->left_child); postorder(ptr->right_child);postorder(ptr->right_child); printf(“%d”, ptr->data);printf(“%d”, ptr->data); }}}}

Page 12: Department of Computer and Information Science, School of Science, IUPUI

Dale Roberts

Example: Expression TreeExample: Expression TreeExampleExample: An Expression Tree: An Expression Tree

1.1. Perform in-order traversal Perform in-order traversal (LNR)(LNR)

A – B + C * E / A – B + C * E / FF

2.2. Perform post-order traversal Perform post-order traversal (LRN)(LRN)

A B – C E F / * A B – C E F / * ++

3.3. Perform pre-order traversal Perform pre-order traversal (NLR)(NLR)

+ - A B * C / E + - A B * C / E FF

+

- *

A B C /

E F

Page 13: Department of Computer and Information Science, School of Science, IUPUI

Dale Roberts

Tree Traversal ExampleTree Traversal ExampleTry your hand at traversing Try your hand at traversing

this tree:this tree:

In-order: (LNR)In-order: (LNR)

Pre-order: (NLR)Pre-order: (NLR)

Post-order: (LRN)Post-order: (LRN)

mar

apr may

jul

feb oct

dec jun nov

sep

null

null

null null

nullnull

null

nullnull nulljan

null

aug

null null

mar

apr may

jul

feb oct

dec jun nov

sep

null

null

null null

nullnull

null

nullnull nulljan

null

aug

null null

Apr, Aug, Dec, Feb, Jan, Jun, Jan, Mar, May, Nov, Oct, Sep

Mar, Apr, Jul, Feb, Dec, Aug,Jun, Jan, May, Sep, Oct, Nov

Aug, Dec, Jan, Jun, Feb, Jul,Apr, Nov, Oct, Sep, May, Mar

Page 14: Department of Computer and Information Science, School of Science, IUPUI

Dale Roberts

Adjacency ListAdjacency ListWe need a computer We need a computer representation for a representation for a graph if we want to use graph if we want to use the computer to solve the computer to solve graph problems. graph problems. One representation is to One representation is to list the nodes, and then list the nodes, and then build a list of connections build a list of connections from each node.from each node.Notice that in this graph, Notice that in this graph, connections are not connections are not directional. If A is directional. If A is connected to B, then B is connected to B, then B is connected to A. connected to A.

Page 15: Department of Computer and Information Science, School of Science, IUPUI

Dale Roberts

Adjacency MatrixAdjacency MatrixFor a graph G with n vertices For a graph G with n vertices we create an we create an nn x x nn boolean (or boolean (or equivalent) matrix. equivalent) matrix. Label the row and columns of Label the row and columns of the matrix with the names of the matrix with the names of the vertices. the vertices. Each element of the matrix Each element of the matrix represents a potential edge in represents a potential edge in the graph as defined by its the graph as defined by its associated vertex pair. associated vertex pair. We set an element of the We set an element of the matrix to TRUE if there is an matrix to TRUE if there is an edge connecting the two edge connecting the two corresponding vertices.corresponding vertices.Notice that the matrix is Notice that the matrix is symmetric along diagonal.symmetric along diagonal.Connections can be give Connections can be give weights to represent the cost weights to represent the cost or distance between nodes.or distance between nodes.

What’s a problem withthis approach?

Page 16: Department of Computer and Information Science, School of Science, IUPUI

Dale Roberts

Dynamic Adjacency MatrixDynamic Adjacency MatrixA dynamic list can be used to represent the actual A dynamic list can be used to represent the actual number of connections in the graph. Not the number of connections in the graph. Not the nn x x nn worst worst case.case.

What problem does thisapproach have that the

matrix approach does not?

Page 17: Department of Computer and Information Science, School of Science, IUPUI

Dale Roberts

SummarySummaryWe have discussed how to represent trees in a computer We have discussed how to represent trees in a computer system.system.Binary Trees restricted to degree <= 2.Binary Trees restricted to degree <= 2.Unrestricted tree that are acyclic graphs.Unrestricted tree that are acyclic graphs.Unrestricted graphs that use adjacency information to Unrestricted graphs that use adjacency information to represent path.represent path.You will receive a programming assignment that You will receive a programming assignment that traverses a graph to list shortest path between two traverses a graph to list shortest path between two points. (You will be given the algorithm.)points. (You will be given the algorithm.)

Page 18: Department of Computer and Information Science, School of Science, IUPUI

Dale Roberts

AcknowledgementsAcknowledgementsHorowitz and Sahni. Data Structures in C++Bob Pilgram. Murray State University.