Skip to content

Commit 115ed93

Browse files
committed
Adding Efficient Solution for Problem - 235 - Lowest Ancestor of BST
1 parent 0548d26 commit 115ed93

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
##==================================
2+
## Leetcode
3+
## Student: Vandit Jyotindra Gajjar
4+
## Year: 2020
5+
## Problem: 230
6+
## Problem Name: Kth Smallest Element in a BST
7+
##===================================
8+
#Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
9+
#
10+
#According to the definition of LCA on Wikipedia:
11+
#“The lowest common ancestor is defined between two nodes p and q as the
12+
#lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
13+
#
14+
#Given binary search tree: root = [6,2,8,0,4,7,9,null,null,3,5]
15+
#
16+
#Example 1:
17+
#
18+
#Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
19+
#Output: 6
20+
#Explanation: The LCA of nodes 2 and 8 is 6.
21+
#Example 2:
22+
#
23+
#Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
24+
#Output: 2
25+
#Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.
26+
class Solution:
27+
def lowestCommonAncestor(self, root, p, q):
28+
if (p.val < root.val and q.val < root.val): #Condition-check: If the values of p and q is in the left subtree
29+
return self.lowestCommonAncestor(root.left, p, q) #Using recursion gives search for the left subtree and return the lowest ancestor
30+
elif (p.val > root.val and q.val > root.val): #Condition-check: If the values of p and q is in the right subtree
31+
return self.lowestCommonAncestor(root.right, p, q) #Using recursion gives search for the right subtree and return the lowest ancestor
32+
else: #Condition-check: Else
33+
return root #We simply return root value

0 commit comments

Comments
 (0)