There are a number of problems in the code. One of them is that it is not a stable type, it can contain anything on the left and right. Another is that setting the local variable node inside the insert function will not affect the change of anything. A stylistic problem, functions that change their arguments, as a rule, have! like the last character in a name, such as insert !, push! SetIndex !.
I think the following should work:
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)
This version overloads pressing Julia! and uses the Nullable type so that it can distinguish between the leaf node and where it needs to continue searching to find where to insert the key. This definition is recursive and not optimized, it would be much faster to do this using loops instead of recursive ones.
source share