如何在Julia中实现二叉搜索树?

如何在Julia中实现二叉搜索树?,julia,Julia,我试图在Julia中实现BST,但在调用insert函数时遇到了问题。当我尝试创建新节点时,结构保持不变 我的代码: type Node key::Int64 left right end function insert(key::Int64, node) if node == 0 node = Node(key, 0, 0) elseif key < node.key insert(key, node.left)

我试图在Julia中实现BST,但在调用insert函数时遇到了问题。当我尝试创建新节点时,结构保持不变

我的代码:

type Node
    key::Int64
    left
    right
end

function insert(key::Int64, node)
    if node == 0
        node = Node(key, 0, 0)
    elseif key < node.key
        insert(key, node.left)
    elseif key > node.key
        insert(key, node.right)
    end
end

root = Node(0,0,0)
insert(1,root)
insert(2,root)
类型节点
密钥::Int64
左边
正确的
结束
函数插入(键::Int64,节点)
如果节点==0
节点=节点(键,0,0)
elseif keynode.key
插入(键,节点。右侧)
结束
结束
根=节点(0,0,0)
插入(1,根)
插入(2,根)
我也试着把零变成零。我尝试的下一个版本是使用节点中定义的数据类型,但当我尝试调用不带任何值的insert(类似于C Null)时,它给了我错误


感谢您的回答。

该代码有许多问题。 一个是它的类型不稳定,左和右可以包含任何内容。 另一个是在insert函数中设置局部变量节点不会影响任何更改。 一个风格问题,修改其参数的函数通常有一个!作为名称中的最后一个字符,如insert!,推setindex

我认为以下措施应该有效:

type BST
    key::Int
    left::Nullable{BST}
    right::Nullable{BST}
end

BST(key::Int) = BST(key, Nullable{BST}(), Nullable{BST}())
BST() = BST(0)

function Base.push!(node::BST, key)
    if key < node.key
        if node.left.isnull
            node.left = BST(key)
        else
            push!(node.left.value, key)
        end
    elseif key > node.key
        if node.right.isnull
            node.right = BST(key)
        else
            push!(node.right.value, key)
        end
    end
end

root = BST()
push!(root, 1)
push!(root, 2)
类型BST
键::Int
左::可为null的{BST}
右::可为null的{BST}
结束
BST(key::Int)=BST(key,可为null的{BST}(),可为null的{BST}())
BST()=BST(0)
函数Base.push!(节点::BST,键)
if keynode.key
如果node.right.isnull
node.right=BST(键)
其他的
推(node.right.value,键)
结束
结束
结束
root=BST()
推(根,1)
推(根,2)

这个版本重载了Julia push!函数,并使用可为null的类型,以便它可以区分叶节点和需要继续搜索以找到插入键的位置。这是一个递归定义,没有经过优化,使用循环而不是递归会快得多。

不确定我是否理解这个问题-您希望
insert
函数做什么?运行代码会在倒数第二行返回
Node(1,0,0)
,在最后一行返回
Node(2,0,0)
,这似乎是正确的?我不确定BST是什么,但读取代码是您试图做的,编写一个以
节点作为输入的函数
(使用字段
key
left
right
)和
key
,然后执行以下两项操作之一:(i)如果未定义
节点
,则使用
key
字段中的
key
参数和
left
right
的零创建一个新的
节点
实例或(ii)如果存在
节点
,则使用函数的
参数更新该节点的
字段?BST表示二元搜索树。函数向结构插入新节点。零表示零。