在红宝石中的二叉树遍历

时间:2014-07-24 11:34:47

标签: ruby string recursion binary-tree

我在Ruby中的二叉树类中编写了一个递归的toString方法。该算法使用两种方法,如下所示。我有一个名为result的局部变量,它用于保存树中所有值的串联。由于某些奇怪的原因,当我在toString算法中连接结果时,树的根发生了变化。

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

因此,我在上面的评论中注意到,树根处的值开始发生变化。它不是与结果连接,而是与更改树的根连接,而不是简单地遍历和连接值。我用过&lt;&lt;和concat。结果相同。有人可以帮忙解释一下吗?我对Ruby很新。谢谢。 :)

1 个答案:

答案 0 :(得分:1)

与其他语言(例如Strings in ruby are not immutable(默认情况下)相反。这意味着,如果currentNode.value.toString返回value实际字符串值(而不是其副本),则调用<<将更改值本身:

class Dummy
  attr_accessor :value
end

dummy = Dummy.new
dummy.value = 'test'

result = dummy.value
result << 'something else'
# => "testsomething else"
dummy.value
# => "testsomething else" # !!!!

为避免这种情况,您需要确保返回值的副本,而不是值本身。

dummy.value = 'test'

result = dummy.value.dup
result << 'something else'
# => "testsomething else"
dummy.value
# => "test" # :-)