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?