Skip to content

Instantly share code, notes, and snippets.

@hoangong
Created December 8, 2015 17:58
Show Gist options
  • Save hoangong/fea50ec382289cf6811e to your computer and use it in GitHub Desktop.
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
/**
* 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