julia - 如何在 Julia 中定义二叉搜索树的类型?

标签 julia union

我尝试使用以下内容在 Julia 中定义整数二叉搜索树的类型:

mutable  struct BST
    key::Int
    left::Union{BST, Nothing}
    right::Union{BST, Nothing}
end

现在我想定义构造函数和基本的 Push!使用这种简单方法的方法:

BST(key::Int) = BST(key, Nothing, Nothing)
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)

当然它不适用于 Julia 1.0!我当然没有正确理解 union 的用法。它们只是抽象类型吗?定义此数据结构的正确方法是什么?

Julia 文档对这个主题的解释很差。

上一个问题涉及现已弃用的 Nullable 类型: How to implement a Binary Search Tree in Julia?

最佳答案

代码如下(假设您不想在 BST 中存储重复值,但我想这就是您想要的):

BST(key::Int) = BST(key, nothing, nothing)
BST() = BST(0)

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

实际上你的定义几乎没问题,只是有一些语法问题:

  • nothing 是一个值,而 Nothing 是一种类型,因此您必须编写 BST(key, Nothing, Nothing) 而不是 BST(键,无,无)
  • 使用这种比较来测试某些东西是否没有node.left === Nothing(使用===,因为编译器可以更轻松地优化此代码)
  • 您必须 push!BST 对象,而不是存储在其中的值,因此 push!(node.right, key)不是 push!(node.right.value, key)

关于julia - 如何在 Julia 中定义二叉搜索树的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52329949/

相关文章:

sql - 由 UNION 形成的表的列名

mongodb - 在 mongoDB 中执行联合

sql-server - INSERT INTO SELECT 使用 UNION 的奇怪顺序

julia - 如何在 InteractiveDynamics.jl 中保存交互式应用程序图形

julia - 反引号表示法中的可选参数

具有可变列表的 Julia 不可变结构

sql - 对来自 Union 的 SQL 结果进行分组

Julia 在 try-catch block 中两次抛出错误

macros - Julia 宏 : @__FILE__ @__LINE__ in macro

algorithm - 联合的时间复杂度