-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathCheckForBalancedTree.py
70 lines (52 loc) · 1.49 KB
/
CheckForBalancedTree.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
# Problem Description: https://practice.geeksforgeeks.org/problems/check-for-balanced-tree/1/
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class Height:
def __init__(self):
self.height = 0
def isBalancedUtil(root, height):
if(not root):
return True
lh = Height()
rh = Height()
l = isBalancedUtil(root.left, lh)
r = isBalancedUtil(root.right, rh)
height.height = 1 + max(lh.height, rh.height)
if(abs(lh.height-rh.height) < 2):
return l and r
return False
def isBalanced(root):
height = Height()
return isBalancedUtil(root, height)
if __name__ == '__main__':
root = None
t = int(input())
for i in range(t):
#root = None
n = int(input())
arr = input().strip().split()
if n == 0:
print(0)
continue
dictTree = dict()
for j in range(n):
if arr[3*j] not in dictTree:
dictTree[arr[3*j]] = Node(arr[3*j])
parent = dictTree[arr[3*j]]
if j is 0:
root = parent
else:
parent = dictTree[arr[3*j]]
child = Node(arr[3*j+1])
if (arr[3*j+2] == 'L'):
parent.left = child
else:
parent.right = child
dictTree[arr[3*j+1]] = child
if isBalanced(root):
print(1)
else:
print(0)