DFS Python


  • 0
    M
    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution:            
        def averageOfLevels(self, root):
            """
            :type root: TreeNode
            :rtype: List[float]
            """
            def helper(root, out, tree, height):
                if len(out) <= height:
                    out.append(0)
                    tree.append(0)
                out[height] += root.val
                tree[height] += 1
                if root.left != None:
                    helper(root.left, out, tree, height + 1)
                if root.right != None:
                    helper(root.right, out, tree, height + 1)
                    
            out = []
            tree = []
            height = 0
            if root == None:
                return out
            helper(root, out, tree, height)
            output = [x/y for x, y in zip(out, tree)]
            return output
            
    

Log in to reply
 

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