Reputation: 3159
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?
Upvotes: 0
Views: 231
Reputation: 35542
Define your resultList outside the function as I see you appending result to this variable. By the way, in order traversal follows this rule. Visit Left, Visit Root and finally Visit Right. However from the code (although I don't know scala), I can decipher that you are visiting left, right and finally root.
A equivalent recursive in-order printing javacode would have looked like this
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
}
}
So, the scala may look like this (syntax may be wrong)
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)
}
}
Here resultList is a variable of type List which should be passed from outside.
Upvotes: 0
Reputation: 579
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
}
Upvotes: 3