Python 二叉搜索树最大值

Python 二叉搜索树最大值,python,binary-tree,binary-search-tree,Python,Binary Tree,Binary Search Tree,我试图在二叉搜索树中找到最大值。下面给出了示例解决方案,但我试图了解我的解决方案是否有任何问题?我对示例解决方案的问题是,它似乎两次检查每个节点是否为None:一次在“if not current.right”中,第二次在“while current…current=current.right”中,这似乎是多余的 样品溶液: def find_largest(root_node): current = root_node while current:

我试图在二叉搜索树中找到最大值。下面给出了示例解决方案,但我试图了解我的解决方案是否有任何问题?我对示例解决方案的问题是,它似乎两次检查每个节点是否为None:一次在“if not current.right”中,第二次在“while current…current=current.right”中,这似乎是多余的

样品溶液:

      def find_largest(root_node):
        current = root_node
        while current:
            if not current.right:
                return current.value
            current = current.right
      def find_largest(root_node):
        current = root_node
        if current:
            while current.right is not None:
                current = current.right
            return current.value
我的解决方案:

      def find_largest(root_node):
        current = root_node
        while current:
            if not current.right:
                return current.value
            current = current.right
      def find_largest(root_node):
        current = root_node
        if current:
            while current.right is not None:
                current = current.right
            return current.value

问题/代码来源:Interviewcake.com

您的分析是正确的,示例解决方案为每个节点检查两次None,您的解决方案只检查一次,否则它们是等效的。我还想说,您的解决方案更具可读性,但这有点主观


作为一种增强,您可以通过调用函数
current
的参数而不是
root\u节点
来去掉函数体中的第一行。它给您带来了额外的好处,因为现在参数名称并不表示只能使用根节点作为参数来调用函数。事实上,它在任何子树中都能正确地找到最大值。

他的if-current有什么原因吗?样本没有检查到这一点。是的,他合并了while和后续的,如果没有。所以使用更多内存的更快方法可能是分配最后一个值,然后说while current.right last=current.right return last。“啊?”乔什说,“当然有原因。如果
root\u node
None
(也就是说,我们得到了一棵空树),会发生什么情况?@joshstrike给网站贴标签或叫名字是不好的。@joshstrike看看这个网站周围,都是有礼貌的帮助者。@PeterWood感谢你努力保持这个网站的礼貌!