I am trying to find the largest value in a binary search tree. The sample solution is given below, but I'm trying to understand if there's anything wrong with my solution? My problem with the sample solution is that it seems to check whether each node is not None twice: once in "if not current.right" and second in "while current ... current = current.right", which seems superfluous.
Sample solution:
def find_largest(root_node):
current = root_node
while current:
if not current.right:
return current.value
current = current.right
My solution:
def find_largest(root_node):
current = root_node
if current:
while current.right is not None:
current = current.right
return current.value
Question/Code source: Interviewcake.com
Your analysis is correct, the sample solution checks for None twice for each node and your solution checks only once, otherwise they are equivalent. I’d also say that your solution is more readable, but that’s somewhat subjective.
As an enhancement, you can get rid of the first line in the body of your function, by calling the argument of the function current instead of root_node. It gives you an extra benefit as now the argument name doesn’t suggest that your function can be called only with the root node as an argument. Indeed, it correctly finds the largest value in any subtree.
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