CS2 OO Design: a restaurant example Trees, tree design, tree traversal

1 / 165
About This Presentation
Title:

CS2 OO Design: a restaurant example Trees, tree design, tree traversal

Description:

... a table in smoking. Waiting for a table in non-smoking. Waiting for a ... Non-smoking. Designing a Solution. We might want to consider sketching some screens: ... –

Number of Views:90
Avg rating:3.0/5.0
Slides: 166
Provided by: monica65
Category:

less

Transcript and Presenter's Notes

Title: CS2 OO Design: a restaurant example Trees, tree design, tree traversal


1
CS2OO Design a restaurant exampleTrees, tree
design, tree traversal
2
Basic Design
  • Software design is an art not a science
  • It is best learned by experience hopefully with
    some expert guidance
  • This lecture will not make you an expert
  • The goal is to give you a simple basic structure
    to get you started in the process.
  • No matter what your major you will take a number
    of design courses before you leave Tech.

3
Simple Steps
  • 1. Understand the problem
  • Problem statement
  • Discussion with clients
  • 2. Develop cases or scenarios
  • Functions that your program must perform
  • Might be menu items
  • Might be events which trigger action
  • 3. Plain English
  • Describe situation
  • Describe scenarios

4
Simple Steps
  • 4. Apply Object Oriented thinking
  • Analyze the plain English
  • Nouns - Objects
  • Verbs - Methods
  • Imagine the structure
  • "has a" relationships (fields)
  • "is a" hierarchical structures
  • Consider communication
  • Who has to communicate with whom?
  • Who has to know about what?

5
Simple Steps
  • 5. Put the design on paper (or the wall)
  • Indicate classes
  • Their methods
  • Their fields
  • Who they need to talk to
  • Indicate hierarchies
  • 6. Run the cases or scenarios against the design
  • Modify, modify, modify
  • 7. Code a class at a time
  • USE A TEST/DEBUG main IN EACH
  • Start at the bottom
  • Compile test frequently

6
An Example
  • A friend owns a restaurant. He knows that youre
    a Java wizard and he asks for your help with a
    little problem.
  • His business is very good and he is so busy that
    his maitre d has trouble keeping track of people
    waiting for tables.
  • He would like a program that would manage the
    various lists of people waiting. These include
  • Waiting for a table in smoking
  • Waiting for a table in non-smoking
  • Waiting for a very big table
  • etc.
  • Since different maitre ds may use different
    techniques he would like something very simple
    and very flexible.

7
An Example
  • After some discussion with your friend you reach
    the following statement of program function
  • The program will display a menu with the
    following choices
  • Create a new list
  • Add a customer to a list
  • Seat a customer from a list
  • Quit
  • This seems like a good starting point although
    you keep in the back of your mind the fact that
    most people will realize they want any given
    program to do more once they see it in operation.

8
Designing a Solution
  • So now you have accomplished the first step
  • 1. Understand the problem
  • Problem statement
  • Discussion with clients
  • Now lets look at the next step
  • 2. Develop cases or scenarios
  • Functions that your program must perform
  • Might be menu items
  • Might be events which trigger action

9
Designing a Solution
  • Lets go back and look at the menu
  • The program will display a menu for the maitre d
    with the following choices
  • Add a new list
  • Add a customer to a list
  • Seat a customer from a list

10
Designing a Solution
  • This seems like a pretty good description of the
    scenarios we need to be able to perform. So this
    will serve as a start for step 3 also
  • 3. Plain English
  • Describe situation
  • Describe scenarios

11
Designing a Solution
  • We might consider adding some additional detail
    and an extra scenario
  • The program will be run by the maitre d of a
    restaurant
  • The program will startup
  • The program will display a menu with the
    following choices
  • Create a new list
  • Add a customer to a list
  • Seat a customer from a list
  • Quit

12
Designing a Solution
  • We might want to consider sketching some screens

MAITRE D Enter 1. To create a new list 2. To
add a customer to a list 3. To seat a customer
from a list 4. To quit Choice 1
13
Designing a Solution
  • We might want to consider sketching some screens

MAITRE D Create a New List Enter the name for
the new list Non-smoking
14
Designing a Solution
  • We might want to consider sketching some screens

MAITRE D Create a New List Enter the name for
the new list Smoking
15
Designing a Solution
  • We might want to consider sketching some screens

MAITRE D Create a New List Enter the name for
the new list Big group
16
Designing a Solution
  • We might want to consider sketching some screens

MAITRE D Add a Customer to a List Enter 1.
For Non-smoking 2. For Smoking 3. For Big
group Choice 2 Enter Customer Smith
17
Designing a Solution
  • We might want to consider sketching some screens

MAITRE D Seat a Customer from a List Enter 1.
For Non-smoking 2. For Smoking 3. For Big
group Choice 1 You may now seat the Jones
party. Press Enter when done. ltENTERgt
18
OO Thinking
  • Lets do the first part of step 4
  • 4. Apply Object Oriented thinking
  • Analyze the plain English
  • Nouns - Objects
  • Verbs - Methods
  • Imagine the structure
  • "has a" relationships (fields)
  • "is a" hierarchical structures
  • Consider communication
  • Who has to communicate with whom?
  • Who has to know about what?

19
Designing a Solution
  • Now lets go back and look at our program
    information
  • The program will be run by the maitre d of a
    restaurant
  • The program will startup
  • The program will display a menu with the
    following choices
  • Create a new list
  • Add a customer to a list
  • Seat a customer from a list
  • Quit
  • Lets mark nouns in blue.

20
Designing a Solution
  • Now lets go back and look at our program
    information
  • The program will be run by the maitre d of a
    restaurant
  • The program will startup
  • The program will display a menu with the
    following choices
  • Create a new list
  • Add a customer to a list
  • Seat a customer from a list
  • Quit
  • Lets mark nouns in blue.
  • Lets mark verbs in red

21
Designing a Solution
  • Now lets go back and look at our program
    information
  • The program will be run by the maitre d of a
    restaurant
  • The program will startup
  • The program will display a menu with the
    following choices
  • Create a new list
  • Add a customer to a list
  • Seat a customer from a list
  • Quit
  • Lets mark nouns in blue.
  • Lets mark verbs in red

22
OO Thinking
  • Now for the remainder well need an additional
    tool
  • 4. Apply Object Oriented thinking
  • ...
  • Imagine the structure
  • "has a" relationships (fields)
  • "is a" hierarchical structures
  • Consider communication
  • Who has to communicate with whom?
  • Who has to know about what?

23
Design Technique
  • The basic building block on Object Oriented
    Programming is the class so lets use some kind
    of symbol for a class. This scheme could be used
    on a big piece of paper, 3 x 5 cards or even a
    whiteboard.

24
Design Technique
  • So our nouns were program, maitre d, restaurant,
    menu, customer, choices, list.
  • Well select some likely candidates for classes
  • Note There is no right/wrong for this step i.e.
    use pencil!

Certainly were going to have some kind of list.
25
Design Technique
  • So our nouns were program, maitre d, restaurant,
    menu, customer, choices, list.
  • Well select some likely candidates for classes
  • Note There is no right/wrong for this step i.e.
    use pencil!

In fact, if we think about it we might want it to
be like a Queue???
26
Design Technique
  • So our nouns were program, maitre d, restaurant,
    menu, customer, choices, list.
  • Well select some likely candidates for classes
  • Note There is no right/wrong for this step i.e.
    use pencil!

Deep in our heart we know that a Queue is
somehow going to require nodes
27
Design Technique
  • So our nouns were program, maitre d, restaurant,
    menu, customer, choices, list.
  • Well select some likely candidates for classes
  • Note There is no right/wrong for this step i.e.
    use pencil!

Well put the Node under the list and come back
to it later
28
Design Technique
  • So our nouns were program, maitre d, restaurant,
    menu, customer, choices, list.
  • Well select some likely candidates for classes
  • Note There is no right/wrong for this step i.e.
    use pencil!

Were also pretty sure that we need some customers
29
Design Technique
  • So our nouns were program, maitre d, restaurant,
    menu, customer, choices, list.
  • Well select some likely candidates for classes
  • Note There is no right/wrong for this step i.e.
    use pencil!

And perhaps a menu?
30
Design Technique
  • So our nouns were program, maitre d, restaurant,
    menu, customer, choices, list.
  • Well select some likely candidates for classes
  • Note There is no right/wrong for this step i.e.
    use pencil!

Maybe well include the Maitre d (Imagine him
holding a clipboard?)
31
Design Technique
  • So our nouns were program, maitre d, restaurant,
    menu, customer, choices, list.
  • Remember, we can always go back and add things.
    At this point we are trying to see the big
    picture...

32
Design Technique
  • Now lets think about some of the things that
    these objects would contain...

33
Design Technique
  • Now lets think about some of the things that
    these objects would contain...

34
Design Technique
  • Now lets think about some of the things that
    these objects would contain...

35
Design Technique
  • Now lets think about some of the things that
    these objects would contain...

36
Design Technique
  • Now look at the fields and also remember the
    verbs run, startup, display, create, add, seat,
    quit.

37
Design Technique
  • Now stop and think about structure
  • Well have lists of Nodes, the Nodes will contain
    Customers, the MaitreD will have perhaps an array
    of lists. Make sense?
  • The Menu class...will instances be different
    menus? Does it need to be a class? Could it just
    be methods in MaitreD?

38
Design Technique
  • Lets consider some scenarios...
  • Startup We might have a small Driver class or
    perhaps just let MaitrD contain the startup main
    java MaitreD

(main)
39
Design Technique
  • Lets consider some scenarios...
  • Startup We would simply have to have a looping
    method that displayed a menu and used a switch to
    do the right thing.

(main)
40
Design Technique
  • Lets consider some scenarios...
  • Create Get the name (maybe the list needs a
    name), make a list object, put it into the array
    of lists. No problem?

(main)
41
Design Technique
  • Lets consider some scenarios...
  • Add Loop through the list array and show the
    list names . Get a choice, then get a customer
    name, create a customer object enqueue it.
    Hmmm, maybe this separate Menu class is not
    helping?

(main)
42
Design Technique
  • Lets consider some scenarios...
  • Note The objective here is not to be pretty!

Class Menu
(main)
Fields choice
Comm
Methods printMenu getChoice
43
Design Technique
  • Okay, maybe neat?

Class MaitreD
(main)
Fields array? of lists
Methods create add seat quit printMenu getChoice

Comm
44
Design Technique
  • Okay, maybe neat?

Class MaitreD
(main)
Fields array? of lists
Methods create add seat quit printMenu getChoice

Comm
45
Design Technique
  • The other scenario is when we wish to seat a
    customer. We assume that a table is now available
    that corresponds to a given list and we simply
    dequeue the head of that list and print out that
    name.

Class MaitreD
(main)
Fields array? of lists
Methods create add seat quit printMenu getChoice

Comm
46
Design Technique
  • What about these "Comm" areas?
  • In this case its pretty straightforward. The
    object/class that creates another object will be
    the one communicating with it so this is simple.
    We would use these for example if a customer
    needed to know about which list he was in.

47
Time for Coding?
  • Stack up the cards or otherwise try to establish
    a bottom up priority for coding.

48
Time for Coding?
  • class Customer
  • private String strName
  • public Customer(String strName)
  • setName(strName)
  • public void setName(String s)
  • strName s
  • public String getName()
  • return strName

49
Time for Coding?
  • // class Customer (continued)
  • public static toString()
  • return getName()
  • public static void main(String args)
  • Customer c1, c2
  • c1 new Customer("Smith")
  • c2 new Customer("Jones")
  • System.out.println(c1 "," c2)
  • c1.setName("Fred")
  • System.out.println(c1.getName())
  • // customer

50
Time to Code
  • Our Node could be specific to this problem.
  • Or we could use the linked list Node (and perhaps
    even the DataNode) we already discussed.
  • Why do we need a special node for a customer?
  • So far we dont.
  • But experience says that perhaps well be adding
    additional information about each customer?

51
Time to Code
  • Our List which we recognize as a Queue type data
    structure could be implemented in several
    different ways
  • We could use an existing Java class such as
    Vector which well discuss in the near future.
  • We could write one of our own.
  • Typical solution in a beginning programming class

52
  • class List
  • private Node head
  • private Node tail
  • private String name
  • public List(String name)
  • setName(name)
  • setHead(null)
  • setTail(null)
  • public void setHead(Node head)
  • this.head head
  • public Node getHead()
  • return head

53
  • // class List (continued)
  • public void setTail(Node tail)
  • this.tail tail
  • public Node getTail()
  • return tail
  • public String getName()
  • return name
  • public void setName(String name)
  • this.name name

54
  • // class List (continued)
  • public boolean isEmpty()
  • return (getHead null)
  • public void add(Object obj)
  • if (isEmpty())
  • setHead(new Node(obj))
  • setTail(getHead())
  • else // add to end
  • getTail().setNext(new Node(o))
  • setTail(getTail().getNext())
  • // add

55
  • // class List (continued)
  • public Object remove()
  • Object retVal
  • if (isEmpty())
  • retVal null
  • else
  • retVal getHead().getData()
  • if(getHead() getTail())
  • setHead(null)
  • setTail(null)
  • else
  • setHead(getHead().getNext())
  • return retVal
  • // remove

56
  • // class List (continued)
  • public String toString()
  • if (isEmpty())
  • return "Empty"
  • else // call the Node classs toString()
  • return getHead().toString()
  • public static void main(String args)
  • List ell new List("TestList")
  • ell.add("Item 1")
  • ell.add("Item 2")
  • System.out.println(ell)
  • System.out.println(ell.remove())
  • System.out.println(ell.remove())
  • if(ell.remove() null)
  • System.out.println("null test passed")
  • // main
  • // List

57
Time to Code
  • Now the method that will get sent to java at
    startup.
  • Lets review what it needs to do
  • Hold a reference to an array of lists
  • Constructor
  • Make the array to hold lists
  • MenuLoop
  • do
  • Print menu
  • Get Choice
  • Switch
  • while (not quit)
  • Main
  • Instantiate
  • Call MenuLoop

58
  • public class MaitreD
  • private List lists
  • int listCount
  • public MaitreD()
  • list new ListMAXARRAY
  • listCount 0
  • // constructor

59
  • // class MaitreD (continued)
  • public void menuLoop()
  • do
  • choice printMenu1()
  • switch(choice)
  • case CREATE
  • create()
  • break
  • case ADD
  • add()
  • break
  • case SEAT
  • seat()
  • break
  • case QUIT
  • break
  • default
  • break

60
  • // MaitreD (continued)
  • private int printMenu1()
  • System.out.print(MENU1)
  • return Integer.parseInt(IOHelper.readLine())
  • // printMenu1
  • private void create()
  • System.out.print(MENU2)
  • listCount
  • if(listCount lt MAXARRAY)
  • listslistCount - 1
  • new List(IOHelper.readLine())
  • else // cannot add the list
  • System.out.println(
  • "Maximum number of lists exceeded -- "

61
  • // MaitreD (continued)
  • private void add()
  • int choice
  • System.out.println(MENU3)
  • for (int i0 i lt listCount i)
  • System.out.print(" " (i1) MENU4)
  • System.out.println(listsi.getListName())
  • System.out.print(MENU5)
  • choice Integer.parseInt(IOHelper.readLine())
  • // Should put error handler here to insure
    valid
  • // list number
  • System.out.print(MENU6)
  • listschoice.add(newCustomer(IOHelper.readLine
    ()))
  • // add

62
  • // MaitreD (continued)
  • private void seat()
  • int choice
  • System.out.println(MENU7)
  • for(int i0 i lt listCount i)
  • System.out.println(" " (i1) MENU4
    listsi.getListName())
  • System.out.print(MENU5)
  • choice Integer.parseInt(IOHelper.readLine())
  • // Would put error handler here to insure valid
  • // list number
  • System.out.println(
  • MENU8 listschoice.remove() MENU9")
  • IOHelper.readLine() // Wait for "Enter"

63
  • // MaitreD (continued)
  • public static void main(String args)
  • // a little testing main
  • MaitreD m new MaitreD()
  • m.menuLoop()

64
  • interface MaitreDConstants
  • public static final int MAXARRAY 20
  • public final static String MENU1
  • "MAITRE D\n\nEnter\n
  • "1. To create a new list\n
  • "2. To add a customer to a list\n
  • "3. To seat a customer from a list\n
  • "4. To quit\n\n
  • "Choice "
  • public final static String MENU2
  • "MAITRE D Create a New List\n\n
  • "Enter the name for the new list "

65
  • // MaitreDConstants (continued)
  • public final static String MENU3
  • "MAITRE D Add a Customer to a List\n\n"
  • "Enter "
  • public final static String MENU4 " For "
  • public final static String MENU5 "Choice "
  • public final static String MENU6
  • "Enter Customer "
  • public final static String MENU7
  • "MAITRE D Seat a Customer from a List\n
  • "Enter\n"
  • public final static String MENU8
  • "You may now seat the "

66
Summary
  • Design before coding.
  • Think OO
  • Nouns,
  • verbs,
  • communication.
  • Code incrementally
  • Test incrementally!
  • Use test mains

67
Questions?
68
Trees
  • Hierarchical data structure
  • Nodes with 0 to many children
  • One special node designated root
  • Acyclic
  • Recursive definition

69
Binary Trees
  • Hierarchical data structure
  • Nodes with 0 to 2 children
  • One special node designated root
  • Acyclic
  • Recursive definition
  • Used for BST

70
Binary Search Trees
  • Binary Tree
  • Left subtree contains key values less than node
  • Right subtree contains key value greater than
    node
  • No duplicates

50
40
95
42
30
Normally handles specially
63
99
37
10
71
Binary Search Trees
  • Performance
  • Search O(log N)
  • Insert O(log N)
  • Traverse O(N)
  • Performance O()'s assume tree is relatively
    balanced

50
50
40
40
95
30
42
30
63
99
10
37
10
72
Data Structure Design
73
Recall Linked ListsSome Design Alternatives
class Object
default behavior
class DataNode
Object data DataNode getData setData equals toStri
ng
class DataNode
74
Recall Linked ListsSome Design Alternatives
class Object
Object data DataNode getData setData equals toStri
ng compareTo
interface Comparable
class DataNode
implements
class DataNode implements Comparable
75
Recall Linked ListsSome Design Alternatives
class Object
interface Comparable
Object data DataNode getData setData equals toStri
ng compareTo
interface DataNodeType
class DataNode
getData setData
interface DataNodeType extends Comparable
class DataNode implements DataNodeType
76
Recall Linked ListsSome Design Alternatives
One Way
class Object
interface Comparable
interface DataNodeType
class DataNode
getData setData
ListNode next ListNode getNext setNext equals toSt
ring compareTo
interface ListNodeType
class ListNode
getNext setNext
interface ListNodeType extends DataNodeType
class ListNode extends DataNode implements
ListNodeType
77
Recall Linked ListsSome Design Alternatives
Another...
class Object
interface Comparable
class DataNode
ListNode next ListNode getNext setNext equals toSt
ring compareTo
interface ListNodeType
class ListNode
getData setData getNext setNext
class ListNode extends DataNode implements
ListNodeType,Comparable
78
Wait, (Bill Monica) have you lost your mind?
  • Well, frankly, yes but let's not talk about that
    now.

79
What's the point?
  • You will design data structure objects like
    ListNodes and TreeNodes (in a second).
  • You will also design container classes like
    LinkedList and BinaryTree
  • You can make your LinkedList hold a ListNode or a
    ListNodeType
  • You can make your BinaryTree hold a TreeNode or a
    TreeNodeType
  • In both cases the latter choice will give you a
    more flexible design.
  • We'll explain why after we talk a little about
    trees

80
Wow!
class Object
interface Comparable
interface DataNodeType
class DataNode
interface ListNodeType
class ListNode
interface TreeNodeType
class TreeNode
81
Or
class Object
interface Comparable
class DataNode
class ListNode
interface ListNodeType
interface TreeNodeType
class TreeNode
82
Or even...
class Object
interface Comparable
class ListNode
interface ListNodeType
interface TreeNodeType
class TreeNode
83
Let's use this one
class Object
interface Comparable
class DataNode
class ListNode
interface ListNodeType
interface TreeNodeType
class TreeNode
84
The Interfaces
  • public interface ListNodeType extends Comparable
  • public void setData(Comparable data)
  • public Comparable getData()
  • public void setNext(ListNodeType next)
  • public ListNodeType getNext()
  • public interface TreeNodeType extends Comparable
  • public void setData(Comparable data)
  • public Comparable getData()
  • public void setLeft(TreeNodeType left)
  • public TreeNodeType getLeft()
  • public void setRight(TreeNodeType right)
  • public TreeNodeType getRight()

85
The Classes
  • public class DataNode implements Comparable
  • private Comparable data
  • public DataNode(Comparable data)
    /Constructor/
  • public void setData(Comparable data)
    /implementation details not shown/
  • public Comparable getData() /implementation/
  • public boolean equals(Object o)
    /implementation/
  • public String toString() /implementation/
  • public int compareTo(Object o)
    /implementation/
  • public static void main(String args)
    /implementation/

86
The Classes
  • public class ListNode extends DataNode implements
    ListNodeType
  • public ListNode(Comparable data)
    /Constructor/
  • public void setNext(ListNodeType next)
    /implementation/
  • public ListNodeType getNext() /implementation/
  • public boolean equals(Object o)
    /implementation/
  • public boolean toString()
  • public static void main(String args)
    /implementation/

87
The Classes
  • public class TreeNode extends DataNode implements
    TreeNodeType
  • public TreeNode(Comparable data)/Constructor/
  • public TreeNode(Comparable data,
  • TreeNodeType left, TreeNodeType right)
    /Constructor/
  • public void setLeft(TreeNodeType left)
    /implementation/
  • public TreeNodeType getLeft() /implementation/
  • public void setRight(TreeNodeType right)
  • /implementation/
  • public TreeNodeType getRight()
    /implementation/
  • public boolean equals(Object o)
    /implementation/
  • public static void main(String args)
    /implementation/
  • public String toString()

88
Java
cs1322
Learning about the Glorious Chairmans Nodes will
promote unity.
89
The Tree Class
  • In a similar fashion to Linked Lists...
  • Now that we have a tree node which has
  • A Comparable data reference (since it's going to
    be a BST)
  • A left and a right reference to another tree node
  • Appropriate nodish methods (equals, compareTo,
    toString()
  • And, of course, a debug main
  • We can design a Tree class

90
What will it need?
  • A reference to a root node
  • A constructor
  • Traverse methods
  • in order
  • preorder
  • postorder
  • breadth first?
  • insert
  • contains
  • nodeCount
  • height
  • delete
  • main

Let's code!
91
  • class Tree
  • private TreeNodeType root
  • public Tree()
  • root null
  • / toString ??? /
  • public void inorder()
  • inorder(root)

92
  • // class Tree (continued)
  • private void inorder(TreeNodeType current)
  • if(current ltgt null)
  • inorder(current.getLeft())
  • System.out.println(current)
  • inorder(current.getRight())

93
Outline of In-Order Traversal
Recall
  • Three principle steps
  • Traverse Left
  • Process current (root) node (Current node)
  • Traverse Right
  • The process can be anything
  • print the node value
  • insert the node in some other structure
  • look for some value
  • do some math with each node
  • etc.
  • Separate process from mechanics of traversal

94
  • Traverse the tree "In order"
  • Visit currents left sub-tree
  • Visit current node process data
  • Visit currents right sub-tree

95
  • // class Tree (continued)
  • public static void main(String args)
  • TreeNode t2 new TreeNode("T2")
  • TreeNode t4 new TreeNode("T4")
  • TreeNode t9 new TreeNode("T9")
  • TreeNode t3 new TreeNode("T3", t2, t4)
  • TreeNode t8 new TreeNode("T8", null, t9)
  • TreeNode t5 new TreeNode("T5", t3, t8)
  • / This is strange /
  • Tree test new Tree()
  • test.root t5 / !!!!!!! Done only to test
    !!! /
  • test.inorder()
  • // End of class (for testing)

5
8
3
2
9
4
96
The other classic traversals
97
  • // class Tree (continued)
  • public void preorder()
  • preorder(root)
  • private void preorder(TreeNodeType current)
  • if(current ltgt null)
  • System.out.println(current)
  • preorder(current.getLeft())
  • preorder(current.getRight())

98
  • // class Tree (continued)
  • public void postorder()
  • postorder(root)
  • private void postorder(TreeNodeType current)
  • if(current ltgt null)
  • postorder(current.getLeft())
  • postorder(current.getRight())
  • System.out.println(current)

99
Other ideas...
100
  • // class Tree (continued)
  • public int countNodes()
  • return countNodes(root)
  • private int countNodes(TreeNodeType current)
  • if(current null)
  • return 0
  • else
  • return 1 countNodes(current.getLeft())
  • countNodes(current.getRight())

101
  • // class Tree (continued)
  • public String toString()
  • return toString(root)
  • private String toString(TreeNodeType current)
  • if(current null)
  • return ""
  • else
  • return toString(current.getLeft())
  • (current.getData() null
  • ? "(null data)" current.getData() )
  • toString(current.getRight())

102
(No Transcript)
103
But why TreeNodeType???
  • Advanced Java Topic

104
Advanced Java Topic
  • Why are we covering advanced topics in an
    introductory course?
  • Okay, it's not that advanced
  • You might be coding Java for money in the near
    future and this is a good thing to understand

105
But why???
  • Here is what makes sense
  • A node should hold Comparables instead of just
    Objects
  • When sorting is important
  • When order is important
  • My LinkedList and my Tree
  • have head references which are ListNodeType and
    TreeNodeType(remember, those are interfaces!)
  • don't actually have to be ListNodes and
    TreeNodes,
  • they just have to implement certain methods.
  • Here is what makes no sense
  • Why would I ever want to put anything but a
    TreeNode in my Tree?
  • Why would I ever want to put anything but a
    ListNode in my list?

106
Performance
  • Suppose you are writing a real application and
    you have a SwissArmyKnife class. It does all
    kinds of cool things (slices, dices, juliennes,
    etc.)
  • Youre going to have about 60,000 SwissArmyKnife
    objects.
  • They will move back and forth between a Tree and
    a LinkedList.
  • The conventional Node-with-a-reference-to-an-objec
    t approach works but there is a lot of overhead
  • Every time we remove a SwissArmyKnife object from
    one structure and put it in the other we have to
    discard a node which must be garbage collected
    and allocate a new Node for the other structure
  • This is costly
  • If instead we just add to SwissArmyKnife the
    appropriate data, next, left and right fields
    along with appropriate accessors and modifiers we
    can actually put the object directly in the list
    or tree (Note This might require modification of
    the LinkedList or Tree class.)

107
Performance
  • In other words, we could have some class of
    interest (SwissArmyKnife) that happens to satisfy
    perhaps both interfaces!
  • TreeNodeType
  • ListNodeType
  • As such, objects from that weird class could be
    stored in a tree, or in a list.
  • This is so because the said object
  • is a TreeNodeType and
  • is a ListNodeType as well!

108
Performance
  • Its like having an amphibious vehicle
  • Satisfies roadVehicleInterface
  • Satisfies waterVehicleInterface
  • Its a car
  • Its a boat
  • It can be stored
  • In the garage
  • In the marina

109
Questions?
  • Okay, then back to it We almost have a BST

110
Inserting into a BST
  • We have a Binary Search Tree
  • It can be empty
  • Or have some elements in it already
  • We want to add an element to it
  • Inserting/adding involves 2 steps
  • Find the correct location
  • Do the steps to add a new node
  • Must maintain "search" structure

111
Finding the Correct Location
Start withthis tree
12
41
3
98
7
112
Finding the Correct Location
Where would 4 be added?
12
41
3
98
7
113
Finding the Correct Location
4
To the topdoesnt work
12
41
3
98
7
114
Finding the Correct Location
12
41
4
98
3
In the middledoesnt work
7
115
Finding the Correct Location
12
41
3
98
7
At the bottomDOES work!
4
116
Finding the Correct Location
  • Must maintain "search" structure
  • Everything to left is less than current
  • Everything to right is greater than current
  • Adding at the "bottom" guarantees we keep search
    structure.
  • Well recurse to get to the "bottom" (i.e. when
    current.getRight() null
  • or current.getLeft() null)

117
Insert
  • As is by now typical to you...
  • We will use a helper module approach
  • The first module check to see if the root is null
  • If it is the new node is added immediately
  • If not, call the helper.
  • Since it knows it will be getting a node it can
    check for which direction to insert
  • If it finds a null reference in that direction,
    add a node
  • If not recurse!

118
Insert
  • public void insert(Comparable c)
  • TreeNode temp new TreeNode(c)
  • if (root null)
  • root temp
  • else
  • insert(root, temp)

119
  • public void insert(TreeNodeType cur, TreeNodeType
    temp)
  • if(cur.compareTo(temp) gt 0)
  • if(cur.getLeft() null)
  • cur.setLeft(temp)
  • else
  • insert(cur.getLeft(), temp)
  • else if(cur.compareTo(temp) lt 0)
  • if(cur.getRight() null)
  • cur.setRight(temp)
  • else
  • insert(cur.getRight(), temp)
  • else
  • throw new RuntimeException("Duplicate node
    found")

120
Questions?
121
Deleting from a BST
122
The Scenario
  • We have a Binary Search Tree and want to remove
    some element based upon a match.
  • Must preserve "search" property
  • Must not lose any elements (i.e. only remove the
    one targeted element)

123
BST Deletion
  • Search for desired item.
  • If not found, then return NULL or print error.
  • If found, perform steps necessary to accomplish
    removal from the tree.

124
Four Scenarios of Deletion
  • Delete a leaf node
  • Delete a node with only one child (left)
  • Delete a node with only one child (right)
  • Delete a node with two children
  • Cases 2 and 3 are comparable and only need slight
    changes in the conditional statement used

125
Delete a Leaf Node
  • Simply make the parent node null. This will
    remove the node from the tree.

126
Delete a Leaf Node
  • Simply make the parent node null. This will
    remove the node from the tree.
  • Lets delete the 42.

127
Delete a Leaf Node
Simply make the parent node null. This will
remove the node from the tree.
128
Delete a Leaf Node
  • Simply make the parent node null. This will
    remove the node from the tree.
  • Ta-Da

129
Questions?
130
Delete a Node with One Child
  • Determine if it has a left or a right child.
  • Move the child reference to the parent reference

131
Delete a Node with One Child
  • Determine if it has a left or a right child.
  • Move the child reference to the parent reference
  • Lets to the 14

132
Delete a Node with One Child
  • Determine if it has a left or a right child.
  • Move the child reference to the parent reference

133
Delete a Node with One Child
  • Determine if it has a left or a right child.
  • Ta-Da

134
Delete a Node with One Child
Determine if it has a left or a right
child. Move the child reference to the parent
reference Now, the 71
135
Delete a Node with One Child
Determine if it has a left or a right
child. Move the child reference to the parent
reference
136
Delete a Node with One Child
Determine if it has a left or a right
child. There!
137
Questions?
138
Delete a Node with Two Children
  • Copy a replacementvalue from a descendentnode.
  • - Largest from left
  • - Smallest from right
  • Then delete that descendent node to remove the
    duplicate value.
  • - We know this will be an easier case.

139
Delete a Node with Two Children
Lets delete 50.
140
Delete a Node with Two Children
Look to the leftsub-tree.
141
Delete a Node with Two Children
Find and copy thelargest value(this will erase
theold value but createsa duplicate).
142
Delete a Node with Two Children
The resulting treeso far.
143
Delete a Node with Two Children
Now delete theduplicate fromthe left sub-tree.
144
Delete a Node with Two Children
The final resultingtree still has the proper
searchstructure.
145
Delete a Node with Two Children
Lets delete 94.
146
Delete a Node with Two Children
Look to the rightsub-tree.
147
Delete a Node with Two Children
Find and copy thesmallest value(this will erase
theold value but createsa duplicate).
148
Delete a Node with Two Children
The resulting treeso far.
149
Delete a Node with Two Children
Now delete theduplicate fromthe left sub-tree.
150
Delete a Node with Two Children
The final resultingtree still has
searchstructure.
151
Delete Overview
  • Deleting a node from a binary search tree
    involves two steps
  • Search for the element
  • Then perform the deletion
  • We must preserve the search structure and only
    delete the element which matches.
  • Four scenarios
  • Deleting a leaf node
  • Deleting a node with only the left child
  • Deleting a node with only the right child
  • Deleting a node with both children

152
On to the code!
153
First some constants...
  • private static final int BOOGABOOGA -1
  • private static final int NOCHILDREN 0
  • private static final int LEFTCHILD 1
  • private static final int RIGHTCHILD 2
  • private static final int TWOCHILDREN 3

154
A handy method
  • private int countChildren(TreeNodeType n)
  • int retval BOOGABOOGA
  • if(n ! null)
  • if(n.getLeft() null n.getRight()
    null)
  • retval NOCHILDREN
  • if(n.getLeft() ! null n.getRight()
    null)
  • retval LEFTCHILD
  • if(n.getLeft() null n.getRight() !
    null)
  • retval RIGHTCHILD
  • if(n.getLeft() ! null n.getRight() !
    null)
  • retval TWOCHILDREN
  • return retval

155
The public method
  • public void delete(Comparable target)
  • root delete(root, target)

156
  • private TreeNodeType delete
  • (TreeNodeType cur, Comparable
    target)
  • TreeNodeType temp
  • TreeNodeType retval null
  • if(cur ! null)
  • if(cur.getData().compareTo(target) 0)
  • switch(countChildren(cur))
  • case NOCHILDREN // No children
  • retval null
  • break
  • case LEFTCHILD // Left child only
  • retval cur.getLeft()
  • break
  • case RIGHTCHILD // Right child only
  • retval cur.getRight()
  • break

157
  • case TWOCHILDREN // Node to delete has two
  • // children
  • retval cur
  • // Special case...
  • left child has null right child
  • if(cur.getLeft().getRight() null)
  • cur.setData(cur.getLeft().getData())
  • cur.setLeft(cur.getLeft().getLeft())
  • else
  • temp cur.getLeft()
  • while
  • (temp.getRight().getRight() !
    null)
  • temp temp.getRight()
  • cur.setData(temp.getRight().getData())
  • temp.setRight(temp.getRight().getLeft())
  • break

158
  • default
  • System.err.println
  • ("The impossible has
    happened!!!")
  • System.exit(0)
  • // end switch removing the cur node
  • else if(cur.getData().compareTo(target) gt 0)
  • // Recursing Left
  • cur.setLeft(delete(cur.getLeft(), target))
  • retval cur
  • else
  • // recursing Right
  • cur.setRight(delete(cur.getRight(), target))
  • retval cur
  • return retval

159
Questions?
160
  • class BigDaddy
  • public BigDaddy()
  • System.out.println("Whos your Daddy?")

161
  • class BadDad extends BigDaddy
  • public BadDad()
  • System.out.println("This is BadDad!")
  • ruin() // which ruin method???
  • public void ruin()
  • // Notice this does NOT get called!
  • System.out.println("Maniacal Laugh!!!")

162
  • class Bad extends BadDad
  • private int x 0 // bad programming!
  • public Bad()
  • System.out.println("Whos Bad?")
  • public void setX(int x)
  • this.x x
  • public int getX()
  • return x
  • public void ruin()
  • System.out.println("About to set x to 42")
  • setX(42)
  • System.out.println("Verifying... x "
    getX())
  • public static void main(String args)
  • Bad b new Bad()
  • System.out.println("Value of x is now "
    b.getX())

163
What's the output?
Whos your Daddy? This is BadDad! About to set x
to 42 Verifying x 42 Whos Bad? Value of x is
now 0
164
Questions?
165
(No Transcript)
Write a Comment
User Comments (0)
About PowerShow.com