From 2bd6acba75cb1d63e2349c104d0e47f08e8fd7d9 Mon Sep 17 00:00:00 2001 From: ivan Date: Thu, 16 Jul 2026 05:19:43 -0600 Subject: [PATCH] adding algo --- ...0_lowest_common_ancestor_of_binary_tree.py | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 src/my_project/interviews/google_top_exercises/round_1/20_lowest_common_ancestor_of_binary_tree.py 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