1
+ # Link to the problem : https://practice.geeksforgeeks.org/problems/lowest-common-ancestor-in-a-bst/1
2
+
3
+
4
+
5
+ #Function to find the lowest common ancestor in a BST.
6
+ def LCA (root , n1 , n2 ):
7
+ #code here.
8
+ while (root ):
9
+ if (root .data > n1 and root .data > n2 ):
10
+ root = root .left
11
+ elif (root .data < n1 and root .data < n2 ):
12
+ root = root .right
13
+ else :
14
+ break
15
+ return root
16
+
17
+ #{
18
+ # Driver Code Starts
19
+ #Initial Template for Python 3
20
+ from collections import deque
21
+ # Tree Node
22
+ class Node :
23
+ def __init__ (self , val ):
24
+ self .right = None
25
+ self .data = val
26
+ self .left = None
27
+
28
+ # Function to Build Tree
29
+ def buildTree (s ):
30
+ #Corner Case
31
+ if (len (s )== 0 or s [0 ]== "N" ):
32
+ return None
33
+
34
+ # Creating list of strings from input
35
+ # string after spliting by space
36
+ ip = list (map (str ,s .split ()))
37
+
38
+ # Create the root of the tree
39
+ root = Node (int (ip [0 ]))
40
+ size = 0
41
+ q = deque ()
42
+
43
+ # Push the root to the queue
44
+ q .append (root )
45
+ size = size + 1
46
+
47
+ # Starting from the second element
48
+ i = 1
49
+ while (size > 0 and i < len (ip )):
50
+ # Get and remove the front of the queue
51
+ currNode = q [0 ]
52
+ q .popleft ()
53
+ size = size - 1
54
+
55
+ # Get the current node's value from the string
56
+ currVal = ip [i ]
57
+
58
+ # If the left child is not null
59
+ if (currVal != "N" ):
60
+
61
+ # Create the left child for the current node
62
+ currNode .left = Node (int (currVal ))
63
+
64
+ # Push it to the queue
65
+ q .append (currNode .left )
66
+ size = size + 1
67
+ # For the right child
68
+ i = i + 1
69
+ if (i >= len (ip )):
70
+ break
71
+ currVal = ip [i ]
72
+
73
+ # If the right child is not null
74
+ if (currVal != "N" ):
75
+
76
+ # Create the right child for the current node
77
+ currNode .right = Node (int (currVal ))
78
+
79
+ # Push it to the queue
80
+ q .append (currNode .right )
81
+ size = size + 1
82
+ i = i + 1
83
+ return root
84
+
85
+
86
+ if __name__ == "__main__" :
87
+ t = int (input ())
88
+ for _ in range (0 ,t ):
89
+ s = input ()
90
+ root = buildTree (s )
91
+ n1 ,n2 = list (map (int ,input ().split ()))
92
+ print (LCA (root ,n1 ,n2 ).data );
93
+
94
+ # } Driver Code Ends
0 commit comments