progs/lecture2.scala
changeset 61 8bdc44963c0c
parent 58 93a2b6e4b84c
child 76 bc0e0aa4dee1
equal deleted inserted replaced
59:8e866d0af03a 61:8bdc44963c0c
   218 
   218 
   219 
   219 
   220 val t1 = Node(4, Node(2, Leaf(), Leaf()), Node(7, Leaf(), Leaf()))
   220 val t1 = Node(4, Node(2, Leaf(), Leaf()), Node(7, Leaf(), Leaf()))
   221 insert(t1, 3)
   221 insert(t1, 3)
   222 
   222 
       
   223 def depth(tr: Tree): Int = tr match {
       
   224   case Leaf() => 0
       
   225   case Node(_, left, right) => 1 + List(depth(left), depth(right)).max
       
   226 }
       
   227 
       
   228 
   223 def balance(tr: Tree): Int = tr match {
   229 def balance(tr: Tree): Int = tr match {
   224   case Leaf() => 0
   230   case Leaf() => 0
   225   case Node(_, left, right) => balance(left) - balance(right)
   231   case Node(_, left, right) => depth(left) - depth(right)
   226 }
   232 }
   227 
   233 
       
   234 balance(insert(t1, 3))
   228 
   235 
   229 // another example
   236 // another example
   230 
   237 
   231 abstract class Person
   238 abstract class Person
   232 case class King() extends Person
   239 case class King() extends Person