Hope you are not cheating in a test.
Edit: This is for n-ary tree rather than binary tree.
This can be done with basic tree traversal with back-tracking.
Here's a Depth-First-Search based Implementation:
class Tree(object):
"Generic tree node. Adapted from https://stackoverflow.com/a/28015122/7562633 "
def __init__(self, value, children=None):
self.value = value
self.children = []
if children is not None:
for child in children:
self.add_child(child)
def add_child(self, node):
assert isinstance(node, Tree)
self.children.append(node)
def __repr__(self):
return str(self.value)
def dfs_find_parent(tree, search_value, parent=None):
"""
Given a subTree `tree` find parent of the `search_value`.
In a DFS manner!
If the root node itself is search_value, return parent
"""
# terminal case that root of subTree is the target value
if tree.value == search_value:
return parent
# otherwise look for target value in the children
for child in tree.children:
found = dfs_find_parent(child, search_value, tree)
if found is not None:
return found
# no match in this tree
return None
# DRIVER CODE:
# 0
# /|\
# 1 2 3
# / \
# 4 5
t = Tree('0', [Tree('1'),
Tree('2'),
Tree('3', [Tree('4'),
Tree('5')])])
for i in range(7):
print("Parent of {} is {}".format(i, dfs_find_parent(t, str(i))))
Output:
Parent of 0 is None
Parent of 1 is 0
Parent of 2 is 0
Parent of 3 is 0
Parent of 4 is 3
Parent of 5 is 3
Parent of 6 is None