File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed
lowest-common-ancestor-of-a-binary-search-tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change 1+ """
2+ 235. Lowest Common Ancestor of a Binary Search Tree
3+ https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
4+ """
5+
6+ # Definition for a binary tree node.
7+ class TreeNode :
8+ def __init__ (self , x ):
9+ self .val = x
10+ self .left = None
11+ self .right = None
12+
13+ """
14+ Solution:
15+ - If both p and q are greater than the root, the lowest common ancestor is in the right subtree.
16+ - If both p and q are less than the root, the lowest common ancestor is in the left subtree.
17+ - Otherwise, the root is the lowest common ancestor.
18+
19+ Time complexity: O(N)
20+ - The function is called recursively for each node
21+ Space complexity: O(N)
22+ - Maximum depth of the recursion is the height of the tree
23+ """
24+
25+ class Solution :
26+ def lowestCommonAncestor (
27+ self , root : "TreeNode" , p : "TreeNode" , q : "TreeNode"
28+ ) -> "TreeNode" :
29+
30+ if p .val > root .val and q .val > root .val :
31+ return self .lowestCommonAncestor (root .right , p , q )
32+
33+ elif p .val < root .val and q .val < root .val :
34+ return self .lowestCommonAncestor (root .left , p , q )
35+ else :
36+ return root
You can’t perform that action at this time.
0 commit comments