diff --git a/trees_and_graphs/lowest_common_ancestor.py b/trees_and_graphs/lowest_common_ancestor.py new file mode 100644 index 0000000..8d96e17 --- /dev/null +++ b/trees_and_graphs/lowest_common_ancestor.py @@ -0,0 +1,25 @@ +''' +Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. +''' + +class ThisTree: + def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': + + def dfs(root, p, q): + + if not root: + return False + + left = dfs(root.left, p, q) + right = dfs(root.right, p, q) + mid = root == p or root == q + + if mid + left + right >= 2: + self.answer = root + + return left or right or mid + + dfs(root, p, q) + + return self.answer +