我一直在学习lua,似乎无法简单地实现这个二叉树的工作......
function createTree(tree, max)
if max > 0 then
tree = {data = max, left = {}, right = {}}
createTree(tree.left, max - 1)
createTree(tree.right, max - 1)
end
end
function printTree(tree)
if tree then
print(tree.data)
printTree(tree.left)
printTree(tree.right)
end
end
tree = {}
createTree(tree, 3)
printTree(tree)
程序在执行后返回nil。我已经在网上搜索了解参数传递如何在lua中工作(如果它是通过引用或值)并且发现某些类型通过引用(如表和函数)传递而其他类型按值传递。不过,我做了全局变量" tree"将表传递给" createTree"功能,我甚至初始化"左"和"对"是" createTree"内的空表出于同样的目的。我做错了什么?
答案 0 :(得分:6)
可能不需要通过新表初始化,而只需要设置其值。
function createTree(tree, max)
if max > 0 then
tree.data = max
tree.left = {}
tree.right = {}
createTree(tree.left, max - 1)
createTree(tree.right, max - 1)
end
end
答案 1 :(得分:5)
试试这个:
function createTree(max)
if max == 0 then
return nil
else
return {data = max, left = createTree(max-1), right = createTree(max-1)}
end
end