# Implementing leaf and non-leaf node by using parametric type

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
``````

Instead of the four last fields you could use two fields (one for each side) that are either `nothing` or a composite internal struct (lets call it `Branch{T}`) that has the two associated fields (`child` and `weights`). Note the `child` and `weights` do not need to support `Nothing` values as the `Branch{T}` will only exist if it exists.

Is the tree complete? (This is, it always has the two branches or none?) What I proposed was slightly different:

``````struct Branch{T, W}
weights::Vector{W}
child::Node{T, W}
end

struct Node{T, W}
value::T
left::Union{Nothing,Branch{W}}
right::Union{Nothing,Branch{W}}
end
``````