Skip to content

Instantly share code, notes, and snippets.

@aniruddha84
Created March 10, 2016 00:31
Show Gist options
  • Save aniruddha84/347897f2f7c95eaabef8 to your computer and use it in GitHub Desktop.
Save aniruddha84/347897f2f7c95eaabef8 to your computer and use it in GitHub Desktop.
Find lowest common ancestor of 2 nodes in a Binary Tree
def find_lca(val1, val2, root)
stack = []
stack.push [root, []]
ancestor_list_val1 = []
ancestor_list_val2 = []
until stack.empty?
t = stack.pop
if t[0].data == val1
ancestor_list_val1 = t[1]
elsif t[0].data == val2
ancestor_list_val2 = t[1]
end
break if !ancestor_list_val1.empty? && !ancestor_list_val2.empty?
new_ancestor_list = t[1].unshift(t.data) # adds parent to start of ancestor list
stack.push [t.right, new_ancestor_list]
stack.push [t.left, new_ancestor_list]
end
if !ancestor_list_val1.empty? && !ancestor_list_val2.empty?
return (ancestor_list_val1 & ancestor_list_val1)[0] # performs intersection of the 2 ancestor lists
end
nil
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment