-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathHeight Of Tree.py
79 lines (61 loc) · 1.36 KB
/
Height Of Tree.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
73
74
75
76
77
78
"""
Height Of Tree
Given a binary tree, find and return the height of given tree.
#### Input format :
Nodes in the level order form (separated by space). If any node does not have left or right child,
take -1 in its place
#### Output format :
Height
#### Constraints :
1 <= N <= 10^5
#### Sample Input :
10
9
4
-1
-1
5
8
-1
6
-1
-1
3
-1
-1
-1
#### Sample Output :
5
"""
import queue
class BinaryTreeNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def height(root):
if root is None:
return 0
leftHeight=height(root.left)
rightHeight=height(root.right)
return 1 + max(leftHeight,rightHeight)
def buildLevelTree():
root = BinaryTreeNode(int(input()))
q = queue.Queue()
q.put(root)
while not q.empty():
currentNode = q.get()
leftChild = int(input())
if leftChild != -1:
leftNode = BinaryTreeNode(leftChild)
currentNode.left =leftNode
q.put(leftNode)
rightChild = int(input())
if rightChild != -1:
rightNode = BinaryTreeNode(rightChild)
currentNode.right =rightNode
q.put(rightNode)
return root
# Main
root = buildLevelTree()
print(height(root))