简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM