Skip to content

Commit ca7481a

Browse files
committed
Check Height Of binary Tree
1 parent 0e4101c commit ca7481a

File tree

1 file changed

+101
-0
lines changed

1 file changed

+101
-0
lines changed

Tree/height_of_a_binary_tree.py

+101
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
2+
'''
3+
# Node Class:
4+
class Node:
5+
def _init_(self,val):
6+
self.data = val
7+
self.left = None
8+
self.right = None
9+
'''
10+
11+
# return the Height of the given Binary Tree
12+
def height(root):
13+
# code here
14+
if root:
15+
return max(height(root.left), height(root.right)) + 1
16+
else:
17+
return 0
18+
19+
20+
21+
#{
22+
# Driver Code Starts
23+
#Initial Template for Python 3
24+
25+
#Contributed by Sudarshan Sharma
26+
from collections import deque
27+
# Tree Node
28+
class Node:
29+
def __init__(self, val):
30+
self.right = None
31+
self.data = val
32+
self.left = None
33+
34+
# Function to Build Tree
35+
def buildTree(s):
36+
#Corner Case
37+
if(len(s)==0 or s[0]=="N"):
38+
return None
39+
40+
# Creating list of strings from input
41+
# string after spliting by space
42+
ip=list(map(str,s.split()))
43+
44+
# Create the root of the tree
45+
root=Node(int(ip[0]))
46+
size=0
47+
q=deque()
48+
49+
# Push the root to the queue
50+
q.append(root)
51+
size=size+1
52+
53+
# Starting from the second element
54+
i=1
55+
while(size>0 and i<len(ip)):
56+
# Get and remove the front of the queue
57+
currNode=q[0]
58+
q.popleft()
59+
size=size-1
60+
61+
# Get the current node's value from the string
62+
currVal=ip[i]
63+
64+
# If the left child is not null
65+
if(currVal!="N"):
66+
67+
# Create the left child for the current node
68+
currNode.left=Node(int(currVal))
69+
70+
# Push it to the queue
71+
q.append(currNode.left)
72+
size=size+1
73+
# For the right child
74+
i=i+1
75+
if(i>=len(ip)):
76+
break
77+
currVal=ip[i]
78+
79+
# If the right child is not null
80+
if(currVal!="N"):
81+
82+
# Create the right child for the current node
83+
currNode.right=Node(int(currVal))
84+
85+
# Push it to the queue
86+
q.append(currNode.right)
87+
size=size+1
88+
i=i+1
89+
return root
90+
91+
92+
if __name__=="__main__":
93+
t=int(input())
94+
for _ in range(0,t):
95+
s=input()
96+
root=buildTree(s)
97+
print(height(root))
98+
99+
100+
101+
# } Driver Code Ends

0 commit comments

Comments
 (0)