Skip to content

Latest commit

 

History

History
49 lines (36 loc) · 1.38 KB

_3157. Find the Level of Tree with Minimum Sum.md

File metadata and controls

49 lines (36 loc) · 1.38 KB

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

Back to top


First completed : July 05, 2024

Last updated : July 05, 2024


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

Acceptance Rate : 68.67 %


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

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

            levelSums[lvl] += curr.val
            lvl += 1
            dfs(curr.left, levelSums, lvl)
            dfs(curr.right, levelSums, lvl)
        
        dfs(root, levelSums)
        return min(levelSums, key=lambda x: levelSums[x])