Skip to content

Latest commit

 

History

History
49 lines (35 loc) · 1.33 KB

_1161. Maximum Level Sum of a Binary Tree.md

File metadata and controls

49 lines (35 loc) · 1.33 KB

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

Back to top


First completed : July 17, 2024

Last updated : July 17, 2024


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

Acceptance Rate : 67.16 %


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 maxLevelSum(self, root: Optional[TreeNode]) -> int:
        lvls = defaultdict(int)

        def dfs(curr: Optional[TreeNode], lvls: defaultdict, lvl: int = 1) -> None :
            if not curr :
                return
            
            lvls[lvl] += curr.val

            dfs(curr.left, lvls, lvl + 1)
            dfs(curr.right, lvls, lvl + 1)

        dfs(root, lvls)
        return max(lvls.keys(), key=lambda x: lvls[x])