Skip to content

Latest commit

 

History

History
51 lines (37 loc) · 1.37 KB

_637. Average of Levels in Binary Tree.md

File metadata and controls

51 lines (37 loc) · 1.37 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


First completed : July 04, 2024

Last updated : July 04, 2024


Related Topics : Tree, Depth-First Search, Breadth-First Search, Binary Tree

Acceptance Rate : 73.33 %


Solutions

Python

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]:
        hs = defaultdict(list)

        def dfs(curr: Optional[TreeNode], depth: int = 0) -> None :
            if not curr :
                return
            
            hs[depth].append(curr.val)
            
            depth += 1
            dfs(curr.left, depth)
            dfs(curr.right, depth)

        dfs(root, 0)
        print(hs)
        return [sum(hs[x]) / len(hs[x]) for x in range(1 + max(hs.keys()))]