Binary Search Tree(二叉搜索树)是一种数据结构,它的每个节点最多只有两个子节点,且左子节点总是小于右子节点。lower()方法可以在二叉搜索树中查找比给定键值小的最大键值。
下面是Python代码示例:
class TreeNode:
def __init__(self, val=None):
self.val = val
self.left = None
self.right = None
class BST:
def __init__(self):
self.root = None
def lower(self, root, key):
if root is None:
return None
if root.val == key:
if root.left is not None:
return self.maximum(root.left)
else:
return None
if root.val > key:
return self.lower(root.left, key)
else:
right = self.lower(root.right, key)
if right is not None:
return right
else:
return root.val
def maximum(self, root):
while root.right is not None:
root = root.right
return root.val
这里定义了一个TreeNode类和一个BST类。lower()方法在BST类中。它接收两个参数:根节点和键值。如果根节点为空,则返回None;如果节点的值等于键值,则返回左子树中最大节点的键值;如果节点的值大于键值,则递归调用左子树,否则递归调用右子树并返回结果中较小的那个节点的键值。
maximum()方法用于查找某个节点的左子树中的最大值。这个方法接收一个参数:根节点。它使用一个while循环来找到最右边的节点,也就是左子树中的最大值。