我一直在尝试在Ruby中实现BinaryTree类,但是我遇到了“stack level too deep”错误,尽管我似乎没有在那段特定的代码中使用任何递归:
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行给出了“堆栈层级太深”的错误。然而,如果我使用Ed S.的解决方案
@left = @right = nil
然后
<<
方法会出现错误:在第22行,undefined method '<<' for nil:NilClass (NoMethodError)
。请问有谁能提供解决方法?我的想法是如果我可以告诉BinaryTree
类变量left
和right
是BinaryTree
实例(即它们的类型为BinaryTree
),那么问题就可以得到解决。我的想法对吗?
initialize
方法并调用另一个BinaryTree.new,然后无限循环重复。这就是为什么你的堆栈溢出了。 - bigpotato