Skip to content

Commit

Permalink
feature: lowest common ancestor of binary search tree revisit dfs rec…
Browse files Browse the repository at this point in the history
…ursive
  • Loading branch information
solairerove committed Jan 12, 2024
1 parent 1f2d834 commit cb807b9
Showing 1 changed file with 6 additions and 5 deletions.
11 changes: 6 additions & 5 deletions trees/LowestCommonAncestorOfABinarySearchTree.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,16 @@ def lowest_common_ancestor(self, root: TreeNode, p: TreeNode, q: TreeNode) -> Op

# O(h) time || O(h) space
def lowest_common_ancestor_dfs(self, root: TreeNode, p: TreeNode, q: TreeNode) -> Optional[TreeNode]:
mn, mx = min(p.val, q.val), max(p.val, q.val)

def dfs(node):
if node.val > mx:
return dfs(node.left)
if not node:
return None

if node.val < mn:
if node.val < p.val and node.val < q.val:
return dfs(node.right)

if node.val > p.val and node.val > q.val:
return dfs(node.left)

return node

return dfs(root)

0 comments on commit cb807b9

Please sign in to comment.