开始使用免费开始使用

在 BST 中查找最小节点

在本练习中,您将练习在二叉搜索树(BST)中查找最小节点。

为测试您的代码,您可以使用下述树:

Graphical representation of a binary search tree.

它已在变量 bst 中预加载(第 14 行):

bst = CreateTree()

您可以使用以下代码(第 15 行)打印 find_min() 方法返回的结果:

print(bst.find_min())

本练习是课程的一部分

Python 中的数据结构与算法

查看课程

练习说明

  • current_node 设为根节点。
  • 在合适的子树上迭代节点。
  • 更新 current_node 的值。

交互式实操练习

通过完成这段示例代码来试试这个练习。

class BinarySearchTree:
  def __init__(self):
    self.root = None

  def find_min(self):
    # Set current_node as the root
    current_node = ____
    # Iterate over the nodes of the appropriate subtree
    while current_node.____:
      # Update current_node
      current_node = current_node.____
    return current_node.data
  
bst = CreateTree()
print(bst.find_min())
编辑并运行代码