我一直想在Ruby中实现二叉树类,但我得到了stack level too deep
错误,但我似乎没有使用任何递归在特定的一段代码:实现二叉树在Ruby中
1. class BinaryTree
2. include Enumerable
3.
4. attr_accessor :value
5.
6. def initialize(value = nil)
7. @value = value
8. @left = BinaryTree.new # stack level too deep here
9. @right = BinaryTree.new # and here
10. end
11.
12. def empty?
13. (self.value == nil) ? true : false
14. end
15.
16. def <<(value)
17. return self.value = value if self.empty?
18.
19. test = self.value <=> value
20. case test
21. when -1, 0
22. self.right << value
23. when 1
24. self.left << value
25. end
26. end # <<
27.
28. end
编辑:我的问题有点偏离轨道。当前的代码设置给了我在第8行的stack level too deep
错误但是,如果我聘请埃德S.的解决方案
@left = @right = nil
那么<<
方法抱怨说:undefined method '<<' for nil:NilClass (NoMethodError)
在22行
任何人都可以建议如何解决这个问题?我的想法是,如果我能以某种方式告诉BinaryTree
类变量left
和right
属于BinaryTree
(即它们的类型是BinaryTree
)的实例,那一切都会好的。我错了吗?
每次调用BinaryTree.new时间,它击中了'initialize'方法,并呼吁另一BinaryTree.new,永远重复。这就是为什么你的堆栈溢出 – Edmund