Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.
Example 1:
Input:
3
/ \
9 20
/ \
7
Output: [3, 14.5, 11]
Explanation:
The average value of nodes on level 0 are 3, on level 1 are 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].
Note:
The range of node ' s value is in the range of 32-bit signed integer.
This title describes:
give us a completely binary tree, and we'll find out the average of nodes for each layer of the two-fork tree
My thoughts:
breadth traversal of a two-fork tree, with a two-dimensional array to store all nodes in each layer
and averaging all the nodes in each layer .
Pseudo Code:
The array in Python is dynamic
with A Levels list, each element is a list of all the nodes in each layer
dynamic generation of the next element and the next level list when the breadth is traversed
1 levels = [[Root]] The root itself is the first layer, levels inside
2 pairs of levels one by one take out the list in the level indicated
(If the empty list is taken out, the last layer is indicated, the loop is out)
2.1 Current list level is a layer with all current layer elements in it
2.2 Append an empty list to levels [] to store the next layer
2.3 One to remove the element inside the level node
if node has left,node.left appended to the next Level list
if node has right,node.right appended to the next Level list
2.4 Calculates the average of all nodes in the current layer, and increases the result list res
My python code:
1 #Definition for a binary tree node.2 #class TreeNode (object):3 #def __init__ (self, x):4 #self.val = x5 #self.left = None6 #self.right = None7 8 classsolution (object):9 defAverageoflevels (self, root):Ten """ One : Type Root:treenode A : Rtype:list[float] - """ -levels = [[Root]]#there will be a breadth of traversal, a new list of each layer, each with nodes in each layer theres = []#to store the average of each layer -i =0 - whileI < Len (levels) andLevels[i]! = []: -Level =Levels[i] +j =0 -temp = 0#temporary variables are used to store the node values of the current layer plus and +Levels.append ([])#turn on a new layer A whileJ <len (level): atnode =Level[j] - ifNode.left is notNone: -Levels[i+1].append (node.left) - ifNode.right is notNone: -Levels[i+1].append (node.right) -temp+=Node.val inJ + = 1 -Res.append (temp/j) toi + = 1 + returnRes
Leetcode algorithm: Average of levels in Binary Tree