Why doesn't this work recursively?

Below is a program in 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
}

I made range method in my binary search tree, implementing in-order traversal algorithm. So it has to work recursively, but it doesn't print anything, List(). How to fix my algorithm? or edit my code?

Answers


I don't know scala, but you need to use list l passed as a parameter into recursive function and use output from rangerec function.

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
}

Need Your Help

Dynamically changing DOM-elements as they get's scrolled into view (performance)

javascript jquery dom

I'm trying to find an efficient algorithm for dynamically loading background-images for a bunch of &lt;li&gt;'s, and are having some efficiency problems. My current code looks like this:

django template question (accessing a list)

python django django-templates

I am writing a template for my first django website.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.