Lowest Common Ancestor of a Binary Search Tree - Leetcode 235 - Trees (Python)

preview_player
Показать описание


Please check my playlists for free DSA problem solutions:

My Favorite Courses:

Data Structures & Algorithms:

Python:

Web Dev / Full Stack:

Cloud Development:

Game Development:

SQL & Data Science:

Machine Learning & AI:
Рекомендации по теме
Комментарии
Автор

Master Data Structures & Algorithms For FREE at AlgoMap.io!

GregHogg
Автор

You could also just have the search function return a TreeNode which is the LCA we are looking for. So:

def search(root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
if not root:
return None

if p.val < root.val and q.val < root.val:
return search(root.left, p, q)

elif p.val > root.val and q.val > root.val:
return search(root.right, p, q)

else:
return root

kavan
Автор

Love your explanations. Please do more problems on LinkedLists, Sliding window, Two Pointers etc. I find your explanations much better than Neetcode🙈

supriya
Автор

class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':

if root.val > max(p.val, q.val):
return self.lowestCommonAncestor(root.left, p, q)
if root.val < min(p.val, q.val):
return self.lowestCommonAncestor(root.right, p, q)
return root

nivethithanmanivannan
Автор

This is a really good explanation. It's so much better than my professor's!

SHIHJUIheh
Автор

Good explanation, i suggest u bring more dp and sliding window problems please 😊

niranjanbhat
Автор

when i am running this I am getting an error in second test case! can any1 explain me where i am going wrong

benedictwilliam
Автор

Another approach that would work is adding nonlocal lca in function scope

philipbrujic
Автор

Title says problem 236 (LCA of a binary tree) but video is on problem 235 (LCA of a binary SEARCH tree)

gaiusjuliuscaesar
Автор

Thanks for the simple explanation. I do have a question about why lca is a list and not a variable. Can you please point me to more explanation about lists being 'proper global variables'? Thanks

ketkiambekar
Автор

Hey Greg, I think O(logN) is correct for time complexity.

jmgpqcx