easy to understand python with comment (BFS)


  • 0
    V
    class Solution(object):
        def averageOfLevels(self, root):
            """
            :type root: TreeNode
            :rtype: List[float]
            """
            #current level queue ,next level queue 
            cq,nq=[root],[]
            
            asw,tasw=[],[]
            while True:
                while cq:#if there still node have not visit in the current level queue
                    now=cq.pop(0)
                    #save the child node to next level queue 
                    if now.left is not None:
                        nq.append(now.left)
                    if now.right is not None:
                        nq.append(now.right)
                    #save the val to calculate the level mean val 
                    tasw.append(now.val)
                #if all the current level node have been visit ,calculate the means of the value 
                tmean=sum(tasw)/(len(tasw)+0.)
                asw.append(tmean)
                tasw=[]
                
                if nq == []:#all node have been visit ,break 
                    break
                else:
                    #otherwise ,set the next level node queue as current level queue
                    #clear the next level node queue
                    #loop until all node have been visit 
                    cq=nq
                    nq=[]
            return asw
                
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.