Skip to content

Instantly share code, notes, and snippets.

@ashalva
Last active May 9, 2018 06:39
Show Gist options
  • Save ashalva/d984dbb2539a49ab74e969d262fe91bb to your computer and use it in GitHub Desktop.
Save ashalva/d984dbb2539a49ab74e969d262fe91bb to your computer and use it in GitHub Desktop.
Lowest common ancestor in swift.
class Tree {
let value: Int
var left: Tree?
var right: Tree?
init(_ v: Int) {
self.value = v
}
}
let root = Tree(1)
let firstRight = Tree(2)
let firstLeft = Tree(3)
let firstLeftLeft = Tree(4)
let firstLeftRight = Tree(6)
let firstRightRight = Tree(7)
let firstRightLeft = Tree(5)
root.left = firstLeft
root.right = firstRight
firstLeft.left = firstLeftLeft
firstLeft.right = firstLeftRight
firstRight.right = firstRightRight
firstRight.left = firstRightLeft
func LCA(_ root: Tree?, _ a: Tree?, _ b: Tree?) -> Tree? {
if root == nil { return nil }
if a?.value == root?.value || b?.value == root?.value { return root }
let left = LCA(root?.left, a, b)
let right = LCA(root?.right, a, b)
if left != nil && right != nil { return root }
if left != nil { return left }
if right != nil { return right }
return nil
}
if let answ = LCA(root, firstRightLeft, firstLeftRight) {
print(answ.value) // result "1\n"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment