defget_common_ancestor(tree, p, q): # if it's a empty tree, or givin nodes not in dict ifnot tree or p notin tree or q notin tree: return
# root node root = [k for k,v in tree.items() if v isNone][0]
# if any givin nodes is root node if tree.get(p) isNoneor tree.get(q) isNone: return root
# recursive helper function defrecursive(tree, rp, rq): if rp == tree.get(rq): return rp # p is children of q if rq == tree.get(rp): return rq # q is children of p if rq == p: return p # q move up, equal p then p if rp == q: return q # p move up, equal q then q if tree.get(rp) == tree.get(rq): # p,q moved to root return tree.get(rp) return recursive(tree, tree.get(rp), tree.get(rq))