Created
December 8, 2015 17:58
-
-
Save hoangong/fea50ec382289cf6811e to your computer and use it in GitHub Desktop.
Lowest common ancestor. One of a very common binary tree puzzle. The implementation in scala is in about 10 lines
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
/** | |
* Lowest common ancestor. One of a very common binary tree puzzle. The implementation in scala is in about 10 lines | |
*/ | |
object Tree { | |
def findLCA(tree: Tree, x: Int, y: Int): Option[Tree] = { | |
if (tree.value == x || tree.value == y) Some(tree) | |
else (if (tree.left != None) findLCA(tree.left.get, x, y) else None, if (tree.right != None) findLCA(tree.right.get, x, y) else None) match { | |
case (Some(r), Some(l)) => Some(tree) | |
case (Some(r), None) => Some(r) | |
case (None, Some(l)) => Some(l) | |
case (None, None) => None | |
} | |
} | |
} | |
case class Tree(value: Int, left: Option[Tree], right: Option[Tree]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment