-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday-22-solution.py
60 lines (51 loc) · 1.32 KB
/
day-22-solution.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
# Data class
class Node:
def __init__(self, data):
self.right = None
self.left = None
self.data = data
# Tree class
class Tree:
def insert(self, root, data):
# If no root, create new root
if root == None:
return Node(data)
else:
# Insert a node in the present tree
if data <= root.data:
# If data is smaller or equal than root value
cur = self.insert(root.left, data)
root.left = cur
else:
# If data is greater than root value
cur = self.insert(root.right, data)
root.right = cur
return root
def get_height(self, root):
# If no root
if root == None:
return -1
else:
# Iterate left and right sub-tree to compute height
left_height = self.get_height(root.left)
right_height = self.get_height(root.right)
if left_height >= right_height:
return 1 + left_height
else:
return 1 + right_height
if __name__ == "__main__":
# Read input integer from stdin
num_test_cases = int(input())
# Instantiate tree class
tree_instance = Tree()
# Set `root` to None
root = None
# Iteratively insert node
for i in range(num_test_cases):
# Read data input integer from stdin
data = int(input())
# Insert data as node
root = tree_instance.insert(root, data)
# Compute height of the tree
height = tree_instance.get_height(root)
print("Height of the tree:", height)