Skip to content

Instantly share code, notes, and snippets.

@binhngoc17
Created November 19, 2014 07:54
Show Gist options
  • Save binhngoc17/cc4d4e1e5c0ae64aa067 to your computer and use it in GitHub Desktop.
Save binhngoc17/cc4d4e1e5c0ae64aa067 to your computer and use it in GitHub Desktop.
Find Common Ancestor of two elements in a BST
import sys
test_cases = open(sys.argv[1], 'r')
bst = {
'datum': 30,
'left': {
'datum': 8,
'left': {
'datum': 3,
'left': None,
'right': None,
},
'right': {
'datum': 20,
'left': {
'datum': 10,
'left': None,
'right': None,
},
'right': {
'datum': 29,
'left': None,
'right': None,
},
},
},
'right': {
'datum': 52,
'left': None,
'right': None,
}
}
def locate_el(val, bst):
if bst == None:
return None
if bst['datum'] == val:
return bst
elif bst['datum'] > val:
return locate_el(val, bst['left'])
else:
return locate_el(val, bst['right'])
def common_parent(bst, el1, el2):
if bst['datum'] == el1 or bst['datum'] == el2:
return bst['datum']
if locate_el(el1, bst['left']) and locate_el(el2, bst['right']):
return bst['datum']
else:
if locate_el(el1, bst['left']) and locate_el(el2, bst['left']):
return common_parent(bst['left'], el1, el2)
else:
return common_parent(bst['right'], el1, el2)
for test in test_cases:
input_str = test.replace('\n', '')
a,b = [int(k) for k in input_str.split(' ')]
print common_parent(bst, a, b)
test_cases.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment