I'm writing a recursive toString method in a binary tree class in Ruby. The algorithm uses two methods as shown below. I have a local variable called result, which is to hold the concatenation of all the values in the tree. For some odd reason, when I concatenate result in the toString algorithm, the root of the tree changes.
def toString
currentNode = @root
result = "<"
if nil != currentNode
result << (getString currentNode, result)
end
result = result + ">"
return result
end
def getString(currentNode, result)
if currentNode != nil
result = currentNode.value.toString
if nil != currentNode.left
result << "," # Through debugging, I have noticed that it starts here!!!!
result.concat (self.getString currentNode.left, result)
end
if nil != currentNode.right
result << ","
result.concat (self.getString currentNode.right, result)
end
end
return result
end
So, where I have noted in the comment above, the value at the root of the tree begins to change. Instead of concatenating with result, it concatenates with the root, which changes the tree, instead of simply traversing and concatenating the values. I have used << and concat. Same result. Could someone please help shed some light on this? I am fairly new to Ruby. Thank you. :)