CSC 212 Trees & Recursion. Announcements Midterm grades were generally good Wide distributions of...

36
CSC 212 Trees & Recursion

Transcript of CSC 212 Trees & Recursion. Announcements Midterm grades were generally good Wide distributions of...

Page 1: CSC 212 Trees & Recursion. Announcements Midterm grades were generally good  Wide distributions of scores, however  Will hand back at end of class

CSC 212

Trees & Recursion

Page 2: CSC 212 Trees & Recursion. Announcements Midterm grades were generally good  Wide distributions of scores, however  Will hand back at end of class

Announcements

Midterm grades were generally goodWide distributions of scores, howeverWill hand back at end of classWill not discuss individual situations until

office hours today

Page 3: CSC 212 Trees & Recursion. Announcements Midterm grades were generally good  Wide distributions of scores, however  Will hand back at end of class

Announcements

Homework #3 results were…not goodRead the homework FAQ regularly

Do not edit my code, unless stated explicitly

Do more tests than what Tester includes But definitely do tests included with Tester Tester checks if code compiles and meets minimum

functionality

Comment your code One assignment submitted without a name

Page 4: CSC 212 Trees & Recursion. Announcements Midterm grades were generally good  Wide distributions of scores, however  Will hand back at end of class

Announcements

Homework #3 results were…not goodCan (re-)submit homework until Thursday

before lab I can resend any files people submitted

Unless you forgot to include your name

Today’s lecture includes several important examples of how to solve problem #3

Page 5: CSC 212 Trees & Recursion. Announcements Midterm grades were generally good  Wide distributions of scores, however  Will hand back at end of class

Trees

Tree data structure represents a hierarchical relationshipComputer directory

csc212/

homeworks/murders.todo

1Kprograms/

LLQueue.java10K

DLNode.java25K

fail.txt3K

really_fail.txt2K

Tree.java20K

Page 6: CSC 212 Trees & Recursion. Announcements Midterm grades were generally good  Wide distributions of scores, however  Will hand back at end of class

Trees

Tree data structure represents a hierarchical relationshipComputer directoriesObject hierarchy

Mammal

Cat Ape

Lion Human Chimpanzee

Professors Yankee Fan

Page 7: CSC 212 Trees & Recursion. Announcements Midterm grades were generally good  Wide distributions of scores, however  Will hand back at end of class

Trees

Tree data structure represents a hierarchical relationshipComputer directoryObject hierarchyTournament

Marist

Marist Fairfield

Siena Fairfield

Canisius

Canisius

Canisius Manhattan

Niagra

Rider Niagra

Canisius

Page 8: CSC 212 Trees & Recursion. Announcements Midterm grades were generally good  Wide distributions of scores, however  Will hand back at end of class

Overloaded Term: Node

We use Node for our linked lists Each of the individual links are a Node Implement Position

Also use Node for trees Each of the locations in the tree are a Node Still implement Position

Node usually used for any of these items Class implementing Position is called Node

Page 9: CSC 212 Trees & Recursion. Announcements Midterm grades were generally good  Wide distributions of scores, however  Will hand back at end of class

Node for Trees

Position ADT still defines single methodelement() – return Object that Position stores

When used for a tree “next” and “prev” may not make sense Instead defines “parent” & “children”

Page 10: CSC 212 Trees & Recursion. Announcements Midterm grades were generally good  Wide distributions of scores, however  Will hand back at end of class

Tree Relationships

Node A is root of the treeRoot node is the node

at the “top” or “start” oftree

A

B DC

G HE F

I J K

Page 11: CSC 212 Trees & Recursion. Announcements Midterm grades were generally good  Wide distributions of scores, however  Will hand back at end of class

Tree Relationships

Nodes B, C, & D are childrenof Node ANode A is parent of

Nodes B, C, & DNode B is sibling of

Node C & D Parent-child relations

are what define a treestructure

A

B DC

G HE F

I J K

Page 12: CSC 212 Trees & Recursion. Announcements Midterm grades were generally good  Wide distributions of scores, however  Will hand back at end of class

Tree Relationships

Nodes A, B, C, & F areinternal nodesA node is “internal” if

it has 1 or more children

A

B DC

G HE F

I J K

Page 13: CSC 212 Trees & Recursion. Announcements Midterm grades were generally good  Wide distributions of scores, however  Will hand back at end of class

Tree Relationships

Nodes D, E, G, H, I, J & Kare external nodes or leavesA node is a leaf if it has

no childrenEvery node is either

external or internal

A

B DC

G HE F

I J K

Page 14: CSC 212 Trees & Recursion. Announcements Midterm grades were generally good  Wide distributions of scores, however  Will hand back at end of class

Tree Properties

Height of tree is longest distance from leaf to rootHeight of this tree is 4

A

B DC

G HE F

I J K

Page 15: CSC 212 Trees & Recursion. Announcements Midterm grades were generally good  Wide distributions of scores, however  Will hand back at end of class

Node Properties

Depth of a node isthe number of levelsin tree above itRoot depth always 0Depth of Node B is 1Depth of Node H is 2

A

B DC

G HE F

I J K

Page 16: CSC 212 Trees & Recursion. Announcements Midterm grades were generally good  Wide distributions of scores, however  Will hand back at end of class

Tree Relationships

Trees are a recursive structureEvery node in the tree defines

it own subtreeNode C is the root

node of this subtree

subtree

A

B DC

G HE F

I J K

Page 17: CSC 212 Trees & Recursion. Announcements Midterm grades were generally good  Wide distributions of scores, however  Will hand back at end of class

Tree Relationships

Trees and subtrees do not needto be very largeNode D is the root

of a rather boring subtree

subtree

A

B DC

G HE F

I J K

Page 18: CSC 212 Trees & Recursion. Announcements Midterm grades were generally good  Wide distributions of scores, however  Will hand back at end of class

Binary Tree

Binary Tree is a tree where each Node can have at most 2 childrenNodes in a binary tree can have 0, 1, or 2

childrenRefer to one child as the “left” child and other

as “right” child

Page 19: CSC 212 Trees & Recursion. Announcements Midterm grades were generally good  Wide distributions of scores, however  Will hand back at end of class

Object-Oriented Design

Important principle of object-oriented design is encapsulationHide implementation detailsRely upon already defined classes & methods

Maximizes code reusability Minimizes amount of testing needed The key is to write as little code as needed…

Page 20: CSC 212 Trees & Recursion. Announcements Midterm grades were generally good  Wide distributions of scores, however  Will hand back at end of class

Implementing a Binary Tree

Binary tree could be implemented using linked data structure:public class BTNode implements Position {protected Object element;protected BTNode parent, left, right;// Define constructor, get & set methods...

}

Implementation is similar to linked-list

Page 21: CSC 212 Trees & Recursion. Announcements Midterm grades were generally good  Wide distributions of scores, however  Will hand back at end of class

Link-based Binary Tree

Conceptual Tree: Actual Tree:

B

CA

D

B

A C

D

Page 22: CSC 212 Trees & Recursion. Announcements Midterm grades were generally good  Wide distributions of scores, however  Will hand back at end of class

Vector-based implementation

Could implement using a Vector Root node stored at rank 0

Left subchild at rank 1Right subchild at rank 2Left subchild’s left subchild at rank 3Left subchild’s right subchild at rank 4Right subchild’s left subchild at rank 5Right subchild’s right subchild at rank 6

Page 23: CSC 212 Trees & Recursion. Announcements Midterm grades were generally good  Wide distributions of scores, however  Will hand back at end of class

Vector-based Implementation

For a node at rank nLeft subchild at rank (2n)+1Right subchild at rank (2n) + 2

Need to add empty ranksfor this to work

0

1 2

5 64

8 9

A

HG

FE

D

C

B

J

3

Page 24: CSC 212 Trees & Recursion. Announcements Midterm grades were generally good  Wide distributions of scores, however  Will hand back at end of class

Vector-based Implementation

Binary tree could be implemented using linked data structure:public class BTNode implements Position {protected Object element;protected boolean parent, left, right;protected int rank;// Define constructor, get & set methods...

}

parent, left, right fields are true if parent/child exists

Page 25: CSC 212 Trees & Recursion. Announcements Midterm grades were generally good  Wide distributions of scores, however  Will hand back at end of class

Vector-based Implementation

How should we start this implementation?public class BTVector extends Vector implements BinaryTree {

– or –

public class BTVector implements BinaryTree {protected Vector vect;

Page 26: CSC 212 Trees & Recursion. Announcements Midterm grades were generally good  Wide distributions of scores, however  Will hand back at end of class

How should we start this implementation?public class BTVector extends Vector implements BinaryTree {

– or –

public class BTVector implements BinaryTree {protected Vector vect;

Vector-based Implementation

Page 27: CSC 212 Trees & Recursion. Announcements Midterm grades were generally good  Wide distributions of scores, however  Will hand back at end of class

Vector-based Implementation

How should we start this implementation?public class BTVector extends LLVector implements BinaryTree {

Violates the encapsulation principle! Exposes the tree’s implementation

This also violates my “laziness” principle Requires us to learn LLVector’s implementation Need to write and test Vector & Binary Tree methods Remember: goal is write as little code as possible

Page 28: CSC 212 Trees & Recursion. Announcements Midterm grades were generally good  Wide distributions of scores, however  Will hand back at end of class

BTVector class

public class BTVector implements BinaryTree {/** vect holds the nodes in the tree. */protected Vector vect;/** size equals the number of elements in * the tree. Empty slots mean cannot use * vect.size(). */ protected int size;// No need to define root field public BTVector() { vect = new LLVector(); size = 0;}

Page 29: CSC 212 Trees & Recursion. Announcements Midterm grades were generally good  Wide distributions of scores, however  Will hand back at end of class

BTVector, continued

public Position root() throws EmptyTreeException {Position retVal = null;if (size == 0) throw new EmptyTreeException();try { retVal = (Position)(vect.elemAtRank(0));} catch (BoundaryViolationException e) { // We know this exception cannot be thrown, but // the try-catch block is needed since the // compiler cannot know this.}return retVal;

}

Page 30: CSC 212 Trees & Recursion. Announcements Midterm grades were generally good  Wide distributions of scores, however  Will hand back at end of class

BTVector, continued

public Position insertLeft(Position v, Object e)...{if ((BTNode)v).getLeft()) throw new InvalidPositionException();BTNode retVal = new BTNode();int parentRank = (BTNode)v).getRank(); retVal.setParent(true);(BTNode)v).setLeft(true);retVal.setRank((parentRank * 2) + 1);size++;try { vect.insertAtRank(retVal.getRank(), retVal);} catch (Exception e) { // Still not needed }return retVal;

}

Page 31: CSC 212 Trees & Recursion. Announcements Midterm grades were generally good  Wide distributions of scores, however  Will hand back at end of class

¡Viva la Laziness!

How was LLVector implemented?

Do you care?

Should you care?

Is BTVector a good class name?

Page 32: CSC 212 Trees & Recursion. Announcements Midterm grades were generally good  Wide distributions of scores, however  Will hand back at end of class

Binary Search Tree

Binary Search Trees are specialization of a Binary TreeBSTs order the data in its nodesLeft child defines subtree whose nodes store

elements with value less than the parent node Right child define subtree with greater elements

Page 33: CSC 212 Trees & Recursion. Announcements Midterm grades were generally good  Wide distributions of scores, however  Will hand back at end of class

Position recursiveInsert(Position node, String name){Position child;// For class, we will assume tree is not empty

// Returns -1 if less, 0 if equal, & 1 if greaterif (name.compareTo((String)node.element()) < 0) child = left(node);else child = right(node);if (child != null) return recursiveInsert(child, name);else if (name.compareTo((String)node.element())<0) return insertLeft(node, name);else return insertRight(node, name);

}

Page 34: CSC 212 Trees & Recursion. Announcements Midterm grades were generally good  Wide distributions of scores, however  Will hand back at end of class

Binary Tree Implementation

How is the Binary Tree implemented?

How do you know?

Did it matter?

Page 35: CSC 212 Trees & Recursion. Announcements Midterm grades were generally good  Wide distributions of scores, however  Will hand back at end of class

Position recursiveInsert(Position node, String name){Position child;// For class, we assume the tree is not empty and // ignore handling exceptions.

// Returns -1 if less, 0 if equal, & 1 if greaterif (name.compareTo((String)node.element()) < 0) child = left(node);else child = right(node);if (child != null) return recursiveInsert(child, name);else if (name.compareTo((String)node.element())<0) return insertLeft(node, name);else return insertRight(node, name);

}

Works with any binary tree implementation!

Page 36: CSC 212 Trees & Recursion. Announcements Midterm grades were generally good  Wide distributions of scores, however  Will hand back at end of class

Daily Quiz

Build binary trees representing tournaments of 1, 2, 4, 8, & 16How many games must the champion win?How many games are played in total?Are there/what are the relationships between:

Number of teams Total number of games played Number of games team must win to win tournament