Skip to content

Commit 52e5ea4

Browse files
committed
Sync LeetCode submission Runtime - 55 ms (34.84%), Memory - 22.1 MB (16.52%)
1 parent eec6888 commit 52e5ea4

File tree

1 file changed

+18
-27
lines changed
  • 0236-lowest-common-ancestor-of-a-binary-tree

1 file changed

+18
-27
lines changed
Lines changed: 18 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# Approach 1: Recursive
22

33
# Time: O(n)
4-
# Space: O(n)
4+
# Space: O(h), h = height of the tree
55

66
# Definition for a binary tree node.
77
# class TreeNode:
@@ -11,30 +11,21 @@
1111
# self.right = None
1212

1313
class Solution:
14-
15-
def __init__(self):
16-
self.ans = None
17-
1814
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

Comments
 (0)