Description:This program returns the output of average of each levels in the binary tree which is done by creating a class node .The successor records that is left(l) and right (r) child are created respectively and by pushing the nodes into temporary queue (temp) and keeping track of the sum (s) of the nodes along with the number of nodes (c) , the average of the nodes on each level by making use of these sum and count values is found.

CODE:

# importing queue
from queue import Queue
# class node is created for binary tree
class node:
def __init__(self, data):
self.val = data
self.l = None
self.r = None
# To find average of node
def avg(root):
q = Queue()
q.put(root)
while (not q.empty()):
# To track the sum and count
#variables are declared
Sum = 0
c = 0
temp = Queue()
while (not q.empty()):
n = q.queue[0]
q.get()
Sum += n.val
c += 1
if (n.l != None):
temp.put(n.l)
if (n.r != None):
temp.put(n.r)
q = temp
print((Sum * 1.0 / c), end = " ")
# Driver code
if __name__ == '__main__':
#The successor records of binary tree
root = node(1)
root.l = node(7)
root.r = node(8)
root.l.l = node(6)
root.l.r = node(4)
root.r.r = node(5)
avg(root)

OUTPUT:

1.0 7.5 5.0

Name | Views | Likes |
---|---|---|

Python program to check for children sum property in a binary tree | 184 | 20 |

Python program to find averages of levels in binary tree | 215 | 17 |

## Comments