diff --git a/src/my_project/interviews/google_top_exercises/round_1/20_lowest_common_ancestor_of_binary_tree.py b/src/my_project/interviews/google_top_exercises/round_1/20_lowest_common_ancestor_of_binary_tree.py new file mode 100644 index 00000000..1b8ca656 --- /dev/null +++ b/src/my_project/interviews/google_top_exercises/round_1/20_lowest_common_ancestor_of_binary_tree.py @@ -0,0 +1,27 @@ +class TreeNode: + def __init__(self, x): + self.val = x + self.left = None + self.right = None + +class Solution: + def lowestCommonAncestor(self, root:TreeNode, p, q): + """ + :type root: TreeNode + :type p: TreeNode + :type q: TreeNode + :rtype: TreeNode + """ + + if not root: + return + elif root.val == p.val or root.val == q.val: + return root + + l = self.lowestCommonAncestor(root.left,p,q) + r = self.lowestCommonAncestor(root.right,p,q) + + if l and r: + return root + else: + return l or r \ No newline at end of file