I just came across this code for finding size of a Binary tree.
public int size() {
return(size(root));
}
private int size(Node node) {
if (node == null) return(0);
else {
return(size(node.left) + 1 + size(node.right));
}
}
I am confused why is it so that there are two methods and one without argument. I can guess that it is some good practice but not able to think of the reason.
OOPs suggests that you should write your business logic in private method.As per my view size method with parameter is private and you logic for counting size is here so no other on(outside the class) can modify or access your logic(through inheritance).You are using another size for returning this size method which has public modifier and other user will use that class for getting size basically other user don't know how you are calculating the size.
One is public
and one is private
. So one is exposed and used externally without any parameters public int size()
, and the other is only used internally and hidden externally private int size(Node)
.
This concept is called encapsulation and is the act of hiding internal details that don't need to be exposed for general consumption in an effort to simplify the usage of the class (or library).
The size
method that takes a Node
is implemented recursively -- it finds the size of the tree from that Node
down. This is not useful outside the binary tree class itself, so it's private
.
The other size
method finds the size of the entire tree, and callers should not have to pass in a Node
; the binary tree already knows what its root is. It's not recursive. It delegates to the other size
method, passing the root
to get the size of the entire tree. It's very useful outside of the class, so it's public
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With