From da0f3fd5d888bde8ba9bc85160fc17c076334724 Mon Sep 17 00:00:00 2001 From: bt3gl <138340846+cypher-bt3gl@users.noreply.github.com> Date: Sat, 29 Jul 2023 17:41:24 -0700 Subject: [PATCH] Create lowest_common_ancestor.py --- trees_and_graphs/lowest_common_ancestor.py | 25 ++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 trees_and_graphs/lowest_common_ancestor.py 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 +