Lowest Common Ancestor of a Binary Search Tree
LeetCode 235 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
Walk down until p and q split.
ನಾನು Lowest Common Ancestor of a Binary Search Tree (LeetCode 235) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — BST ಪ್ಯಾಟರ್ನ್ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.
ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್ನಲ್ಲಿದೆ.
Intuition
In a BST, if both p and q are smaller than the current node, their common ancestor is on the left; if both are larger, it's on the right. Otherwise they split here (or one of them is here), so this node is the answer.
Approach
- 1
Current is p or q → return it.
- 2
Both smaller → go left.
- 3
Both larger → go right.
- 4
Otherwise → current node.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
BST descentPythonO(h) time
class Solution:
def lowestCommonAncestor(self, root, p, q):
if root == p or root == q:
return root
cur = root.val
if cur > p.val and cur > q.val:
return self.lowestCommonAncestor(root.left, p, q)
elif cur < p.val and cur < q.val:
return self.lowestCommonAncestor(root.right, p, q)
return rootLowest Common Ancestor of a Binary Search Tree — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು
Lowest Common Ancestor of a Binary Search Tree ಹಿಂದಿನ intuition ಏನು?
In a BST, if both p and q are smaller than the current node, their common ancestor is on the left; if both are larger, it's on the right. Otherwise they split here (or one of them is here), so this node is the answer.
Lowest Common Ancestor of a Binary Search Tree (LeetCode 235) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?
1. Current is p or q → return it. 2. Both smaller → go left. 3. Both larger → go right. 4. Otherwise → current node.
Lowest Common Ancestor of a Binary Search Tree ನ time ಮತ್ತು space complexity ಎಷ್ಟು?
Time: O(h). Space: O(h) recursion. (Accepted approach: BST descent.)
Lowest Common Ancestor of a Binary Search Tree ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?
An iterative loop uses O(1) space.