val l = List(List(9,8),8,List(12)) def leafSum(l: List[Any]): Int = l.map(_ match { case l: List[Any] => leafSum(l) case x: Int => x case _ => 0 }).sum println(leafSum(l))
/****************************************/
//使用新方法实现
sealed abstract class BinaryTree case class Leaf(value: Int) extends BinaryTree case class Node(left:BinaryTree,right: BinaryTree) extends BinaryTree val n = Node(Node(Leaf(3),Leaf(8)),Leaf(5)) def leafSum(bt:BinaryTree):Int = bt match { case Node(left,right) => leafSum(left) + leafSum(right) case Leaf(value) => value } print( leafSum(n) == 16)/*******************************///扩展使每个节点可以有任意多的后代sealed abstract class BinaryTree case class Leaf(value: Int) extends BinaryTree case class Node(bt:BinaryTree*) extends BinaryTree val n = Node(Node(Leaf(3),Leaf(5)),Leaf(2),Node(Leaf(5))) def leafSum(bt:BinaryTree):Int = bt match { case Node(bts @ _*) => bts.map(leafSum).sum case Leaf(value) => value } print( leafSum(n))/********************************************///每个非叶子节点存放操作符sealed abstract class BinaryTree case class Leaf(value: Int) extends BinaryTree case class Node(operator: Char,bt:BinaryTree*) extends BinaryTree val n = Node('+', Node('*', Leaf(3), Leaf(8)), Leaf(2), Node('-', Leaf(5))) def eval(bt:BinaryTree):Int = bt match { case Node('+',bts @ _*) => bts.map(eval).sum case Node('-',bts @ _*) => bts.map(eval).foldLeft(0)(_ - _) case Node('*',bts @ _*) => bts.map(eval).product case Leaf(value) => value case _ => 0 } print( eval(n))