-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathTwoTreesIdentical.py
72 lines (63 loc) · 1.97 KB
/
TwoTreesIdentical.py
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
# Problem Description: https://practice.geeksforgeeks.org/problems/determine-if-two-trees-are-identical/1/
class Node:
def __init__(self, val):
self.right = None
self.data = val
self.left = None
class Tree:
def createNode(self, data):
return Node(data)
def insert(self, node, data, ch):
if node is None:
return self.createNode(data)
if (ch == 'L'):
node.left = self.insert(node.left, data, ch)
return node.left
else:
node.right = self.insert(node.right, data, ch)
return node.right
def search(self, lis, data):
# if root is None or root is the search data.
for i in lis:
if i.data == data:
return i
def isIdentical(root1, root2):
if(not root1 and not root2):
return True
if(root1 and root2):
return (root1.data == root2.data) and isIdentical(root1.left, root2.left) and isIdentical(root1.right, root2.right)
return False
# Driver Program
if __name__ == '__main__':
t = int(input())
for i in range(t):
n = int(input())
arr = input().strip().split()
tree = Tree()
lis = []
root1 = None
root1 = tree.insert(root1, int(arr[0]), 'L')
lis.append(root1)
k = 0
for j in range(n):
ptr = None
ptr = tree.search(lis, int(arr[k]))
lis.append(tree.insert(ptr, int(arr[k+1]), arr[k+2]))
k += 3
n = int(input())
arr = input().strip().split()
tree = Tree()
lis = []
root2 = None
root2 = tree.insert(root2, int(arr[0]), 'L')
lis.append(root2)
k = 0
for j in range(n):
ptr = None
ptr = tree.search(lis, int(arr[k]))
lis.append(tree.insert(ptr, int(arr[k+1]), arr[k+2]))
k += 3
if isIdentical(root1, root2):
print(1)
else:
print(0)