优化二叉树中的替换函数是尾递归的

时间:2016-02-21 18:45:57

标签: scala recursion

我正在尝试优化此函数,以便在Scala中进行尾递归。

  /**
   * Replaces all instances of the original tree with the replacement tree
   * @param originalTree - the tree that needs to be replaced
   * @param replacementTree - the tree that is being put into the original tree
   * @param parentTree - the tree that is being searched for instances to replace
   * @tparam T
   * @return
   */
  def replace[T](originalTree : BinaryTree[T], replacementTree : BinaryTree[T])(implicit parentTree : BinaryTree[T] = this) : BinaryTree[T] = {
    //TODO: Optimize this into a tail recursive function
    parentTree match {
      case Empty => if (originalTree == Empty) replacementTree else Empty
      case l : Leaf[T] => if (l == originalTree) replacementTree else l
      case n : Node[T] => if (n == originalTree) replacementTree else
        Node(n.v,
          replace(originalTree,replacementTree)(n.l),
          replace(originalTree,replacementTree)(n.r))
    }
  }

正如Scaladoc所说,它用originalTree取代parentTreereplacementTree的所有实例。

这是一个非常简单的递归函数,但是将它优化为尾递归函数正在绊倒我。

我已经开始使用以下结构在replace内构建辅助函数

@tailrec
def loop(tree : BinaryTree[T], accum : List[Node[T]]) : BinaryTree[T] = tree match {
  case Empty => if (originalTree == Empty) replacementTree else Empty
  case Leaf(x) => if (Leaf(x) == tree) replacementTree else Leaf(x)
  case Node(v,l,r) => ???

}

以下是BinaryTreeNode

的定义

0 个答案:

没有答案