Hello everyone,
I would like to implement a binary tree by using the parametric type instead of inheritance.
The structure is something like
# leaf node
struct Node{T}
vale::T
first_weights::Nothing
second_weights::Nothing
lchild::Nothing
rchild::Nothing
end
#non-leaf node
struct Node{T}
vale::T
first_weights::Vector{T}
second_weights::Vector{T}
lchild::Node{T}
rchild::Node{T}
end
For a leaf node, the types of first_weights
, second_weights
, lchild
and rchild
are Nothing
.
The idea I have so far is
struct Node{T,W<:Union{Vector{T},Nothing},ND<:Union{Node,Nothing}}
val::T
first_weights::W
second_weights::W
lchild::ND
rchild::ND
end
However, this design allows the possibility, for example
# an unreasonable Node
struct Node{T}
vale::T
first_weights::Vector{T}
second_weights::Vector{T}
lchild::Nothing
rchild::Nothing
end
How can I avoid this problem? Is there any better ways to design this structure? Thanks.
Solution provided by @Henrique_Becker: defining a internal structure Branch
.
struct Node{T}
value::T
branch::Union{Nothing,Branch{T}}
end
struct Branch{T}
first_weights::Vector{T}
second_weights::Vector{T}
lchild::Node{T}
rchild::Node{T}
end