0

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?

3
  • You may not have noticed but those methods are not doing the same thing... Commented Jun 28, 2018 at 12:33
  • You mean because "_put" is used recursively? I don't see why this code can't be moved to "put" and it be used recursively instead. Commented Jun 28, 2018 at 12:39
  • There's more to _put than being called recursively... Commented Jun 28, 2018 at 13:08

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.