Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "CSC 212 Trees & Recursion. Announcements Midterm grades were generally good  Wide distributions of scores, however  Will hand back at end of class "— Presentation transcript:

1 CSC 212 Trees & Recursion

2 Announcements Midterm grades were generally good  Wide distributions of scores, however  Will hand back at end of class  Will not discuss individual situations until office hours today

3 Announcements Homework #3 results were…not good  Read 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

4 Announcements Homework #3 results were…not good  Can (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

5 Trees Tree data structure represents a hierarchical relationship  Computer directory csc212/ homeworks/ murders.todo 1K programs/ LLQueue.java 10K DLNode.java 25K fail.txt 3K really_fail.txt 2K Tree.java 20K

6 Trees Tree data structure represents a hierarchical relationship  Computer directories  Object hierarchy Mammal Cat Ape LionHumanChimpanzee ProfessorsYankee Fan

7 Trees Tree data structure represents a hierarchical relationship  Computer directory  Object hierarchy  Tournament Marist Fairfield SienaFairfield Canisius Manhattan Niagra RiderNiagra Canisius

8 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

9 Node for Trees Position ADT still defines single method  element() – return Object that Position stores When used for a tree “next” and “prev” may not make sense  Instead defines “parent” & “children”

10 Tree Relationships Node A is root of the tree  Root node is the node at the “top” or “start” of tree A B D C GH E F I J K

11 Tree Relationships Nodes B, C, & D are children of Node A  Node A is parent of Nodes B, C, & D  Node B is sibling of Node C & D Parent-child relations are what define a tree structure A B D C GH E F I J K

12 Tree Relationships Nodes A, B, C, & F are internal nodes  A node is “internal” if it has 1 or more children A B D C GH E F I J K

13 Tree Relationships Nodes D, E, G, H, I, J & K are external nodes or leaves  A node is a leaf if it has no children  Every node is either external or internal A B D C GH E F I J K

14 Tree Properties Height of tree is longest distance from leaf to root  Height of this tree is 4 A B D C GH E F I J K

15 Node Properties Depth of a node is the number of levels in tree above it  Root depth always 0  Depth of Node B is 1  Depth of Node H is 2 A B D C GH E F I J K

16 Tree Relationships Trees are a recursive structure  Every node in the tree defines it own subtree  Node C is the root node of this subtree subtree A B D C GH E F I J K

17 Tree Relationships Trees and subtrees do not need to be very large  Node D is the root of a rather boring subtree subtree A B D C GH E F I J K

18 Binary Tree Binary Tree is a tree where each Node can have at most 2 children  Nodes in a binary tree can have 0, 1, or 2 children  Refer to one child as the “left” child and other as “right” child

19 Object-Oriented Design Important principle of object-oriented design is encapsulation  Hide implementation details  Rely upon already defined classes & methods Maximizes code reusability Minimizes amount of testing needed The key is to write as little code as needed…

20 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

21 Link-based Binary Tree Conceptual Tree:Actual Tree: B C A D   BACD  

22 Vector-based implementation Could implement using a Vector Root node stored at rank 0  Left subchild at rank 1  Right subchild at rank 2  Left subchild’s left subchild at rank 3  Left subchild’s right subchild at rank 4  Right subchild’s left subchild at rank 5  Right subchild’s right subchild at rank 6

23 Vector-based Implementation For a node at rank n  Left subchild at rank (2n)+1  Right subchild at rank (2n) + 2 Need to add empty ranks for this to work 0 12 5 6 4 8 9 A HG FE D C B J 3

24 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

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

26 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

27 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

28 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; }

29 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; }

30 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; }

31 ¡Viva la Laziness! How was LLVector implemented? Do you care? Should you care? Is BTVector a good class name?

32 Binary Search Tree Binary Search Trees are specialization of a Binary Tree  BSTs order the data in its nodes  Left child defines subtree whose nodes store elements with value less than the parent node Right child define subtree with greater elements

33 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 greater if (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); }

34 Binary Tree Implementation How is the Binary Tree implemented? How do you know? Did it matter?

35 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 greater if (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!

36 Daily Quiz Build binary trees representing tournaments of 1, 2, 4, 8, & 16  How 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


Download ppt "CSC 212 Trees & Recursion. Announcements Midterm grades were generally good  Wide distributions of scores, however  Will hand back at end of class "

Similar presentations


Ads by Google