Using Obersver Pattern to count nodes in binary search tree
posted 3 years ago
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.
Counter : Size changed to 1
Inserted 4 to the left of 43
Counter : Size changed to 2
Inserted 254 to the right of 43
Counter : Size changed to 3
Inserted 3 to the left of 4
Inserted 5 to the right of 4
Inserted 6 to the right of 5
Inserted 78 to the left of 254
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.