Can any body help to explain why the following ruby code causes stack
overflow? I am new to Ruby. Can’t figure out what the problem is.
code:
class Node
attr_reader :data, :left, :right
attr_writer :data, :left, :right
def initialize(data, left = nil, right = nil)
@data, @left, @right = data, left, right
end
def to_s
“#{@data}, #{@left}, #{@right}”
end
def printPreorder
puts self
@left.printPreorder if @left
@right.printPreorder if @right
end
def printPostorder
@left.printPostorder if @left
@right.printPostorder if @right
puts self
end
def printInOrder
@left.printInOrder if @left
puts self
@right.printInOrder if @right
end
end
n = Node.new(0)
n1 = Node.new(1, n)
n.right = n1
n.printInOrder
ricol
#2
Ricol Wang wrote in post #1170235:
Can any body help to explain why the following ruby code causes stack
overflow? I am new to Ruby. Can’t figure out what the problem is.
n = Node.new(0)
n1 = Node.new(1, n) # so n1 is the root, with n as left side
n.right = n1 # so n right child is n1 !!!
your tree is a graph…
ricol
#3
Yes, you are right! Thank you!
ricol
#4
Regis d’Aubarede wrote in post #1170260:
Ricol Wang wrote in post #1170235:
Can any body help to explain why the following ruby code causes stack
overflow? I am new to Ruby. Can’t figure out what the problem is.
n = Node.new(0)
n1 = Node.new(1, n) # so n1 is the root, with n as left side
n.right = n1 # so n right child is n1 !!!
your tree is a graph…
Yes, you are right! Thank you!