AC Python, super straight forward and easy to understand

  • 0

    I transformed the tree into a list of nodes at each depth, then found the average of each of those lists. Not the more efficient, but very straight forward to quick PASS during the contest!

    def __init__(self):
        self.depth_node_list = {}
    def averageOfLevelsHelper(self, node, depth):
        if node is None:
            return None
        if depth in self.depth_node_list:
            self.depth_node_list[depth] = [node.val]
        self.averageOfLevelsHelper(node.left, depth+1)
        self.averageOfLevelsHelper(node.right, depth+1)
    def averageOfLevels(self, root):
        :type root: TreeNode
        :rtype: List[float]
        result = []
        if root == None:
            return []
        self.averageOfLevelsHelper(root, 0)
        for key, node_list in self.depth_node_list.items():
            sum = 0.0
            cnt = 0.0
            for val in node_list:
                sum += val
                cnt += 1.0
        return result

Log in to reply

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