views:

104

answers:

1

I'm trying to make a binary tree in scala and need to make a method for it so I'm trying to make functions inside the class that deals with children and parent. I want to make the parent a Tree so that I can recursively call it in another function called getPath but I can't create a Tree inside the Tree class. this is the code:

case class Tree[+T](value: T, left: Option[Tree[T]], right: Option[Tree[T]]) {
   var parent: Tree[T] = null

   //method for setting the parent of tree.
   //this method returns the parent TREE instead of the parent value
   //so if you want to use it to find the value, you need to get the parent.value
   def setParent(tree: Tree[T]) {
 parent = tree
   }

   //method for returning the parent
   //the parent is a tree so you have to .value it to get the root
   def getParent(): Tree[T] = parent

   //setting parents of left child and right child if they are not empty trees
   if(left != None) {
      left.get.setParent(this)
   }
   if(right != None) {
      right.get.setParent(this)
   }
}

def getPath[T](tree: Tree[T]):List[T] = {
   if(tree.getParent == null) List(tree.value)
   List(tree.value)++getPath(tree.getParent())
}

I can set the T to Any and it'll work but then I can't recursively call it if you do. Can anyone help me or has another way to get a tree's parent?

+5  A: 

Cleaning up your code a little, I get to:

case class Tree[+T](value: T, left: Option[Tree[T]], right: Option[Tree[T]]) {
  @reflect.BeanProperty   
  var parent: Tree[T] = null

  //setting parents of left child and right child if they are not empty trees
  Seq(left, right).flatten.foreach(_.setParent(this))
}

object Tree {
  def getPath[T](tree: Tree[T]):List[T] = List(tree.value) ++
    (if(tree.getParent == null) 
      Nil
    else
      getPath(tree.getParent()))
}

This fails to compile with:

tree-parent.scala:1: error: covariant type T occurs in contravariant position in type Tree[T] of parameter of setter parent_=

The type parameter T appears in types produced (getter for parent) and consumed (setter for parent) by this interface. Accordingly, it must be invariant:

case class Tree[T]
retronym
Thank you. I'm amazed at how you refined my amateur code the way you did. I hope one day I'll be able to do the same. Thank you!
FireDragonMule