Created
March 10, 2016 00:31
-
-
Save aniruddha84/347897f2f7c95eaabef8 to your computer and use it in GitHub Desktop.
Find lowest common ancestor of 2 nodes in a Binary Tree
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
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