Created
June 10, 2015 08:41
-
-
Save asarkar/f14a8672caad99bb7dab to your computer and use it in GitHub Desktop.
Scala Pattern Matching Demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
sealed abstract class BinaryTree | |
case class BinTreeLeaf(value: Int) extends BinaryTree | |
case class BinTreeNode(left: BinaryTree, right: BinaryTree) extends BinaryTree | |
def leafSum(tree: BinaryTree): Int = tree match { | |
case node: BinTreeNode => leafSum(node.left) + leafSum(node.right) | |
case leaf: BinTreeLeaf => leaf.value | |
} | |
"Method leafSum" should "traverse a binary tree in order" in { | |
/** | |
* . | |
* . . | |
* 1 3 7 5 | |
*/ | |
val BinaryTree = BinTreeNode(BinTreeNode(BinTreeLeaf(1), BinTreeLeaf(3)), BinTreeNode(BinTreeLeaf(7), BinTreeLeaf(5))) | |
leafSum(BinaryTree) should be(16) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment