r/dailyprogrammer • u/rya11111 3 1 • Apr 24 '12
[4/24/2012] Challenge #43 [easy]
Today is a common interview question.
Given a binary tree t and two elements of the tree, m and n, with m < n, find the lowest element of the tree (farthest from the root) that is an ancestor of both m and n.
11
Upvotes
3
u/bubinhead Apr 30 '12
What if m and n are on the same level? They won't share any ancestors. Am I missing something?
2
u/Cosmologicon 2 3 Apr 24 '12
I love recursive algorithms on trees so here's mine:
This should work for trees in general. I don't really see how to optimize it for when it's a binary tree like in the problem....
2
u/luxgladius 0 0 Apr 24 '12
Pseudocode
Call as lowest_ancestor(t,m,n)
2
u/drb226 0 0 Apr 25 '12
Relies heavily on the fact that
m < n, and operates under the assumption that we are dealing with a binary tree.1
u/juanfeng Apr 24 '12
Python
Test case: http://code.google.com/p/keith-novak-open-source-life/source/browse/trunk/algorithm/python/common_ancestor.py