-
Notifications
You must be signed in to change notification settings - Fork 0
/
Kth common ancestor in BST.cpp
83 lines (60 loc) · 1.79 KB
/
Kth common ancestor in BST.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
class Solution:
def kthCommonAncestor(self, root, k, x, y):
# Code here
#{
# Driver Code Starts
#Initial Template for Python 3
from collections import deque
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Function to Build Tree
def buildTree(str):
# Corner Case
if len(str) == 0 or str[0] == 'N':
return None
# Creating list of strings from input string after splitting by space
ip = str.split()
# Create the root of the tree
root = Node(int(ip[0]))
# Push the root to the queue
queue = deque()
queue.append(root)
# Starting from the second element
i = 1
while queue and i < len(ip):
# Get and remove the front of the queue
currNode = queue.popleft()
# Get the current node's value from the string
currVal = ip[i]
# If the left child is not null
if currVal != "N":
# Create the left child for the current node
currNode.left = Node(int(currVal))
# Push it to the queue
queue.append(currNode.left)
# For the right child
i += 1
if i >= len(ip):
break
currVal = ip[i]
# If the right child is not null
if currVal != "N":
# Create the right child for the current node
currNode.right = Node(int(currVal))
# Push it to the queue
queue.append(currNode.right)
i += 1
return root
for _ in range(int(input())):
s = input()
root = buildTree(s)
k, x, y = map(int, input().split())
if root is None:
continue
if root.left is None and root.right is None:
continue
ob = Solution()
print(ob.kthCommonAncestor(root, k, x, y))