LeetCode 235. Lowest Common Ancestor of a Binary Search Tree (Algorithm Explained)

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


Preparing For Your Coding Interviews? Use These Resources
————————————————————

Other Social Media
----------------------------------------------

Show Support
------------------------------------------------------------------------------

#coding #programming #softwareengineering
Рекомендации по теме
Комментарии
Автор

Hey! There is another problem on leetcode which is literally the same exact thing but not a 'binary SEARCH tree', its considered Medium difficulty and I came up with a really inefficient solution haha. Would love to see you explain that since the tree nodes are not sorted. I find your videos really helpful bro, especially this time of year. Keep it up, looking forward to great content!

jaspreets
Автор

wow! that's easy! Thank you
Python:



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


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

if p.val > root.val and q.val > root.val:
return self.lowestCommonAncestor(root.right, p, q)




return root

hassansmallah
Автор

That's awesome! Watching your videos has become my new daily routine.

ziqixu
Автор

bro everytime you explain a solution it sounds so easy 😭GOAT

pealhasan
Автор

runtime error: member access within null pointer of type 'TreeNode'

dunkyzhang
Автор

i think there is a problem, if p and q is 0, and 5 in the first example then it would just return the root?which is not correct

levente
Автор

Your explanation and problem solving is great. I would also like to know the time complexity and space complexity with explanation as these will be expected by any interviewer. :)

nagarjunareddypadala
Автор

You treat problems as if they are nothing. I like that attitude so much. Makes any problem easier.

rishabhjain
Автор

where is base case if root is null and why its not there?

AbhishekSharma-kcic
Автор

What will happen in the case of two nodes directly connected to each other?

anmolbindroo
Автор

This is so beautiful Nick..Thanks for the explanation.

somyasrivastava
Автор

some test cases are failing on leetcode for this solution

harenderbhardwaj
Автор

This will throw null pointer exception if root itself is null

sharmadenesh
Автор

this solution will create null pointer exception.

samspeaks-hkvp
Автор

Correction in the code :
if(p->val == root->val || q->val == root->val)
return root;

This will be the first thing to check. Thanks for the solution @Nick White

AniketSomwanshi-llmz
Автор

This solution only works for the Binary Search Tree (BST) and not for the General Binary Tree.

prashantsah