我这里在 README
中已经提到这个问题,并写出了相关代码 GitHub - nesteiner/BinaryTree.jl: 二叉树 written in Julia
本来是在 Slack
问的,可是没人理我
这里简单说一下,我定义了一个二叉树节点类型
abstract type BinaryTreeNode{T} end
mutable struct BinaryTreeNil{T} <: BinaryTreeNode{T} end
mutable struct BinaryTreeCons{T} <: BinaryTreeNode{T}
data::T
left::Union{BinaryTreeCons{T}, BinaryTreeNil{T}}
right::Union{BinaryTreeCons{T}, BinaryTreeNil{T}}
end
我又自定义了迭代器类型,比如中序遍历迭代器
mutable struct InOrderIterator{T} <: BinaryTreeIterator{T}
node::BinaryTreeNode{T}
length::Int
end
inorder(tree::AbstractBinaryTree{T}) where T = InOrderIterator{T}(tree.root, length(tree))
现在的问题是,我写的中序遍历方法出问题了,使用 collect(inorder(tree))
的时候有好几个数据是 #undef
的
这是我参考 Java
迭代器写的代码
function iterate(iterator::InOrderIterator{T}) where T
current = iterator.node
if isnil(current)
return nothing
end
stack = Stack(BinaryTreeNode{T})
while !isnil(current)
push!(stack, current)
current = left(current)
end
result = top(stack)
pop!(stack)
# assign back
iterator.node = right(result)
# return statement
return result, stack
end
function iterate(iterator::InOrderIterator{T}, stack::Stack{BinaryTreeNode{T}}) where T
current = iterator.node
if isempty(stack)
return nothing
end
while !isnil(current)
push!(stack, current)
current = left(current)
end
result = top(stack)
pop!(stack)
# assign back
iterator.node = right(result)
# return
return result, stack
end
教程在这里 https://blog.csdn.net/u010157717/article/details/41266873
现在的问题是如何修正我的代码,哪位大佬能绑下忙