Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Size method for binary trees

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.

like image 775
Andy897 Avatar asked Oct 03 '13 18:10

Andy897


3 Answers

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.

like image 151
kailash gaur Avatar answered Nov 12 '22 16:11

kailash gaur


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).

like image 28
Daniel Imms Avatar answered Nov 12 '22 18:11

Daniel Imms


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.

like image 45
rgettman Avatar answered Nov 12 '22 18:11

rgettman