Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

This is my implementation of a binary tree in Scala. How can this be made better?

abstract class BinaryTreeNode[+A]

case class MyBinaryTreeNode[A](var data: A,var left: BinaryTreeNode[A],var right: BinaryTreeNode[A]) (implicit ordering: Ordering[A]) extends BinaryTreeNode[A] {

    override def toString = data + " " + left.toString + " " + right.toString
}

case object MyNilNode extends BinaryTreeNode[Nothing]

class MyBinaryTree[A](var head: BinaryTreeNode[A]) {

    def isBST(implicit order: Ordering[A]): Boolean = {
        this.isBSTHelper(head)._1
    }

    def isBSTHelper(node: BinaryTreeNode[A])(implicit order: Ordering[A]): (Boolean, A, A) = {
        node match {
            case MyNilNode =>
                return (true, null.asInstanceOf[A], null.asInstanceOf[A])
            case MyBinaryTreeNode(data, lNode, rNode) =>
                if(lNode == MyNilNode && rNode == MyNilNode) {
                    return (true, data, data)
                }

                val leftResult = this.isBSTHelper(lNode)(order)
                val rightResult = this.isBSTHelper(rNode)(order)
                return (leftResult._1 && rightResult._1 && data >= leftResult._3 && data <= rightResult._2, 
                        leftResult._2,
                        rightResult._3)
        }
    }
}
share|improve this question

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.