-- 定义二叉搜索树节点结构
local function createNode(value)
return { value = value, left = nil, right = nil }
end
-- 插入节点到二叉搜索树
local function insert(root, value)
if root == nil then
return createNode(value)
end
if value < root.value then
root.left = insert(root.left, value)
elseif value > root.value then
root.right = insert(root.right, value)
end
return root
end
-- 在二叉搜索树中搜索值
local function search(root, value)
if root == nil or root.value == value then
return root
end
if value < root.value then
return search(root.left, value)
else
return search(root.right, value)
end
end
-- 创建一个二叉搜索树
local tree = nil
tree = insert(tree, 5)
tree = insert(tree, 3)
tree = insert(tree, 7)
tree = insert(tree, 2)
tree = insert(tree, 4)
-- 在二叉搜索树中搜索值
local result = search(tree, 4)
if result then
print("值 4 存在于二叉搜索树中")
else
print("值 4 不存在于二叉搜索树中")
end
【Lua】 简易二叉树
最新推荐文章于 2024-09-14 22:17:52 发布