|
1 | | -# Approach: Recursive approach from Lowest Common Ancestor of a Binary Tree (https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/) |
| 1 | +# Approach 1: Depth First Search |
2 | 2 |
|
3 | 3 | # Time: O(n) |
4 | 4 | # Space: O(n) |
|
11 | 11 | # self.right = None |
12 | 12 |
|
13 | 13 | class Solution: |
14 | | - |
15 | | - def __init__(self): |
16 | | - self.ans = None |
17 | | - |
18 | 14 | def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': |
19 | | - |
20 | | - def recurse_tree(curr_node) -> bool: |
21 | | - # If reached end of branch, return False |
22 | | - if not curr_node: |
| 15 | + def dfs(node, target): |
| 16 | + # Base case: target found |
| 17 | + if node == target: |
| 18 | + return True |
| 19 | + # Base case: reached null, target not found |
| 20 | + if node is None: |
23 | 21 | return False |
24 | | - |
25 | | - left = recurse_tree(curr_node.left) |
26 | | - right = recurse_tree(curr_node.right) |
27 | | - |
28 | | - # If the current node is one of p or q |
29 | | - mid = curr_node == p or curr_node == q |
30 | | - |
31 | | - # If any two of the three flags (left, right, mid) become True |
32 | | - if mid + left + right >= 2: |
33 | | - self.ans = curr_node |
34 | | - |
35 | | - # Return true if either of the three bool values is True |
36 | | - return mid or left or right |
37 | | - |
38 | | - recurse_tree(root) |
39 | | - return self.ans |
40 | | - |
| 22 | + # Recursive case: search target in left or right subtree |
| 23 | + return dfs(node.left, target) or dfs(node.right, target) |
| 24 | + |
| 25 | + def LCA(node, p, q): |
| 26 | + if node is None or node == p or node == q: |
| 27 | + return node |
| 28 | + |
| 29 | + left = LCA(node.left, p, q) |
| 30 | + right = LCA(node.right, p, q) |
| 31 | + |
| 32 | + # If p and q are found in different subtrees, current node is their LCA |
| 33 | + if left and right: |
| 34 | + return node |
| 35 | + elif left: |
| 36 | + return left |
| 37 | + else: |
| 38 | + return right |
| 39 | + |
| 40 | + # Step 1: Find the lowest common ancestor of nodes p and q |
| 41 | + ans = LCA(root, p, q) |
| 42 | + |
| 43 | + # Step 2: Check if the LCA is p, meaning q must be in p's subtree |
| 44 | + if ans == p: |
| 45 | + return p if dfs(p, q) else None |
| 46 | + |
| 47 | + # Step 3: Check if the LCA is q, meaning p must be in q's subtree |
| 48 | + elif ans == q: |
| 49 | + return q if dfs(q, p) else None |
| 50 | + |
| 51 | + # Step 4: If neither p nor q is the ancestor of the other, return the LCA |
| 52 | + return ans |
0 commit comments