5

假设我有一些使用案例类构建的树,如下所示:

abstract class Tree
case class Branch(b1:Tree,b2:Tree, value:Int) extends Tree
case class Leaf(value:Int) extends Tree
var tree = Branch(Branch(Leaf(1),Leaf(2),3),Branch(Leaf(4), Leaf(5),6))

现在我想构建一种方法来将具有某个 id 的节点更改为另一个节点。这个节点很容易找到,但是不知道怎么改。有没有简单的方法可以做到这一点?

4

3 回答 3

3

这是一个非常有趣的问题!正如其他人已经指出的那样,您必须更改从根到要更改的节点的整个路径。不可变映射非常相似,您可以通过 Clojure 的 PersistentHashMap学到一些东西。

我的建议是:

  • 更改TreeNode。你甚至在你的问题中称它为节点,所以这可能是一个更好的名字。
  • 拉到value基类。再一次,您在问题中谈到了这一点,所以这可能是合适的地方。
  • 在您的替换方法中,请确保如果 aNode及其子项均未更改,则不要创建新的Node.

注释在下面的代码中:

// Changed Tree to Node, b/c that seems more accurate
// Since Branch and Leaf both have value, pull that up to base class
sealed abstract class Node(val value: Int) {
  /** Replaces this node or its children according to the given function */
  def replace(fn: Node => Node): Node

  /** Helper to replace nodes that have a given value */
  def replace(value: Int, node: Node): Node =
    replace(n => if (n.value == value) node else n)
}

// putting value first makes class structure match tree structure
case class Branch(override val value: Int, left: Node, right: Node)
     extends Node(value) {
  def replace(fn: Node => Node): Node = {
    val newSelf = fn(this)

    if (this eq newSelf) {
      // this node's value didn't change, check the children
      val newLeft = left.replace(fn)
      val newRight = right.replace(fn)

      if ((left eq newLeft) && (right eq newRight)) {
        // neither this node nor children changed
        this
      } else {
        // change the children of this node
        copy(left = newLeft, right = newRight)
      }
    } else {
      // change this node
      newSelf
    }
  }
}
于 2012-02-03T16:28:15.120 回答
2

由于您的树结构是不可变的,因此您必须更改从节点到根的整个路径。当您访问您的树时,请保留已访问节点的列表,然后按照 pr10001 的建议,使用复制方法将所有节点更新到根节点。

于 2012-02-03T14:18:54.030 回答
1

copy方法:

val tree1 = Branch(Branch(Leaf(1),Leaf(2),3),Branch(Leaf(4), Leaf(5),6))
val tree2 = tree1.copy(b2 = tree1.b2.copy(b1 = Leaf(5))
// -> Branch(Branch(Leaf(1),Leaf(2),3),Branch(Leaf(5), Leaf(5),6))
于 2012-02-03T14:15:35.787 回答