Reputation: 867
I'm looking at the Binary Search Trees section in the tutorial "Problem Solving with Algorithms and Data Structures", (http://interactivepython.org/runestone/static/pythonds/Trees/SearchTreeImplementation.html). On several occasions, they use "public" and "private" helper methods with the same name, e.g. for the "put" method:
def put(self,key,val):
if self.root:
self._put(key,val,self.root)
else:
self.root = TreeNode(key,val)
self.size = self.size + 1
def _put(self,key,val,currentNode):
if key < currentNode.key:
if currentNode.hasLeftChild():
self._put(key,val,currentNode.leftChild)
else:
currentNode.leftChild = TreeNode(key,val,parent=currentNode)
else:
if currentNode.hasRightChild():
self._put(key,val,currentNode.rightChild)
else:
currentNode.rightChild = TreeNode(key,val,parent=currentNode)
I also have seen this approach elsewhere, but I don't really understand the motivation. What is the advantage compared to putting everything directly into one method, is it just to improve readability?
Upvotes: 0
Views: 43
Reputation: 1868
Here, the motivation is to use recursion. As you probably notice, _put
method calls itself and method signatures are different. If you put _put
method into public method, you have to change signature of public method to handle put operation on a given node. Simply, you have to add currentNode
parameter. However, original public method does not have this parameter. I assume, it is because the author does not want to expose this functionality to end user.
Upvotes: 1
Reputation: 29099
The rationale is that the user of the class should not know anything about "current node". The current node only makes sense during the recursive insert process, it's not a permanent property of the tree. The user treats the tree as a whole, and only does insert/lookup operations on that.
That said, you could mix both methods into one, by using a default value currentNode=None
and checking it. However, the two methods are doing significantly different things. The put
method just initialises the root, while the _put
does the recursive insertion, so it would probably be better to keep them separate.
Upvotes: 1