Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Using Obersver Pattern to count nodes in binary search tree

 
claudia alvarado
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So I have designed a binary search tree class..and on instruction of my teacher, rather than being composed of nodes, the tree is made up of other Binary Trees--it's children are created by inserting new binary trees. We are needing to create a Counter class that is an observer of the size change of the tree and we need to count the number of 'nodes' But I can't figure out how to notify on just every insert call...b/c if I notify on the creation of a new tree--my 'nodeCount' gets reset everytime in the the constructor...any ideas? Thanks!!

Here is my BST class



and here is my counter class



and here is my output..I lose the counter after 3...

Please enter as many integers as you'd like, hit 'Q' when you are finished.

43
Counter : Size changed to 1
4
Inserted 4 to the left of 43
Counter : Size changed to 2
254
Inserted 254 to the right of 43
Counter : Size changed to 3
3
Inserted 3 to the left of 4
5
Inserted 5 to the right of 4
6
Inserted 6 to the right of 5
78
Inserted 78 to the left of 254
 
Rob Spoor
Sheriff
Pie
Posts: 20495
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your observer is only listening for changes to the root node. It isn't attached to the child nodes, so if these change (left.insert, right.insert) it isn't called. You would need to attach all observers to the child nodes if you create them.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic