Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary search tree largest value

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

like image 548
randomUser47534 Avatar asked May 22 '26 16:05

randomUser47534


1 Answers

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.

like image 69
kirelagin Avatar answered May 24 '26 04:05

kirelagin