|
1 | 1 | # Approach 1: Recursive |
2 | 2 |
|
3 | 3 | # Time: O(n) |
4 | | -# Space: O(n) |
| 4 | +# Space: O(h), h = height of the tree |
5 | 5 |
|
6 | 6 | # Definition for a binary tree node. |
7 | 7 | # class TreeNode: |
|
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: |
23 | | - 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 | | - |
| 15 | + # Base case: if root is None or root is one of the nodes we're looking for |
| 16 | + if root is None or root == p or root == q: |
| 17 | + return root |
| 18 | + |
| 19 | + # Recursively search in left and right subtrees |
| 20 | + left = self.lowestCommonAncestor(root.left, p , q) |
| 21 | + right= self.lowestCommonAncestor(root.right, p, q) |
| 22 | + |
| 23 | + # If both left and right return non-null values, |
| 24 | + # then current node is the LCA |
| 25 | + if left and right: |
| 26 | + return root |
| 27 | + |
| 28 | + # If only one side returns a non-null value, |
| 29 | + # return that value up the tree |
| 30 | + return left if left else right |
| 31 | + |
0 commit comments