Recursive Classes - Design Pattern needed

S

syswizard

I've got a class defined that instantiates itself internally. (It's a
simple binary tree implementation). Are there any OO gurus here can
help me to design the proper class structure so that I can track the
item count (# of nodes in the b-tree) and other statistics that would
apply to all instantiations ?
Do I just need to create a separate "parent" class that is
instantiated on the first instance of the bintree class ? I would
guess the parent class would house a Collection to track each instance
of the bintree, as well as the total count of the nodes.....correct ?
Am I on the right track ?
 
T

Tushar Mehta

I've got a class defined that instantiates itself internally. (It's a
simple binary tree implementation). Are there any OO gurus here can
help me to design the proper class structure so that I can track the
item count (# of nodes in the b-tree) and other statistics that would
apply to all instantiations ?
Do I just need to create a separate "parent" class that is
instantiated on the first instance of the bintree class ? I would
guess the parent class would house a Collection to track each instance
of the bintree, as well as the total count of the nodes.....correct ?
Am I on the right track ?
You could do what you propose. But for (almost) the same amount of
programming, I would add the information to each node. Now, you will
know how many elements each and every node contains. Something along
the lines of the pseudocode:

class BinTreeNode:

Dim Left as BinTreeNode, Right as BinTreeNode, _
Val, ChildCount as Integer

private function checkAndAdd(CurrNode as BinTreeNode, NewVal) _
as Boolean
if CurrNode is nothing then
set currnode=new BinTreeNode
with CurrNode
.val = NewVal
.ChildCount=0
end with
checkAndAdd=true
else
checkAndAdd=CurrNode.NewNodeAdded(NewVal)
end if
public function NewNodeAdded(NewVal) as Boolean
if me.val > NewVal then NewNodeAdded=checkAndAdd(me.left,NewVal) _
else NewNodeAdded=checkAndAdd(me.right,NewVal)
if NewNodeAdded then me.ChildCount += 1
end function

Similarly, any delete function would have to subtract one from the
ChildCount property.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top