【问题标题】:Why doesn't this work recursively?为什么这不能递归地工作?
【发布时间】:2012-01-11 05:36:24
【问题描述】:

以下是 Scala 中的程序。

def range(low : Int, high : Int) : List[Int] = {
    var result : List[Int] = Nil
    result = rangerec(root, result, low, high)
    result
}

private def rangerec(r : Node, l : List[Int], low : Int, high :Int) : List[Int] = {
      var resultList : List[Int] = List()
      if(r.left != null) {
        rangerec(r.left, resultList, low, high)
      } else if(r.right != null) {
        rangerec(r.right, resultList, low, high)
      } else {
        if(r.key >= low && r.key <= high) {
            resultList = resultList ::: List(r.key)
            resultList
        } 
      }
      resultList
}

我在我的二叉搜索树中创建了 range 方法,实现了中序遍历算法。所以它必须递归地工作,但它不打印任何东西,List()。如何修复我的算法?还是编辑我的代码?

【问题讨论】:

    标签: algorithm scala data-structures recursion recursive-datastructures


    【解决方案1】:

    我不知道 scala,但您需要使用 list l 作为参数传递给递归函数并使用 rangerec 函数的输出。

    private def rangerec(r : Node, l : List[Int], low : Int, high :Int) : List[Int] = {
          var resultList : List[Int] = l
          if(r.left != null) {
            resultList = rangerec(r.left, l, low, high)
          } else if(r.right != null) {
            resultList = rangerec(r.right, l, low, high)
          } else {
            if(r.key >= low && r.key <= high) {
                resultList = l ::: List(r.key)
            } 
          }
          resultList
    }
    

    【讨论】:

      【解决方案2】:

      当我看到你将结果附加到这个变量时,在函数之外定义你的结果列表。顺便说一句,为了遍历遵循这个规则。访问左,访问根,最后访问右。但是从代码中(虽然我不知道 scala),我可以破译你正在访问左,右,最后是 root。

      等效的递归按顺序打印 javacode 看起来像这样

       public void printOrdered(Node node){
        if(node.left != null){
         printOrdered(node.left); //VISIT LEFT
        }
        System.out.println(node.data); //VISIT ROOT AND PRINT
        if(node.right!=null){
         printOrdered(node.right); //VISIT RIGHT
        }
       }
      

      所以,scala 可能看起来像这样(语法可能是错误的)

      private def rangerec(r : Node) : Void = {
            if(r.left != null) {
              rangerec(r.left)
            } 
            resultList = resultList :: List(r.key)
            if(r.right != null) {
              rangerec(r.right)
            }
      }
      

      这里的resultList是一个List类型的变量,应该从外部传入。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-09-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-13
        • 1970-01-01
        • 2013-11-02
        相关资源
        最近更新 更多