Given the root of a binary tree root where each node has a value, return the level of the tree that has the minimum sum of values among all the levels (in case of a tie, return the lowest level).
Note that the root of the tree is at level 1 and the level of any other node is its distance from the root + 1.
Example 1:
Input:root = [50,6,2,30,80,7]
Output:2
Explanation:
Example 2:
Input:root = [36,17,10,null,null,24]
Output:3
Explanation:
Example 3:
Input:root = [5,null,5,null,5]
Output:1
Explanation:
Constraints:
The number of nodes in the tree is in the range [1, 105].
1 <= Node.val <= 109
Solutions
Solution 1: BFS
We can use Breadth-First Search (BFS) to traverse the binary tree level by level, record the sum of the node values at each level, and find the level with the smallest sum of node values, then return the level number.
The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes in the binary tree.
1 2 3 4 5 6 7 8 910111213141516171819202122232425
# 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 = rightclassSolution:defminimumLevel(self,root:Optional[TreeNode])->int:q=deque([root])ans=0level,s=1,infwhileq:t=0for_inrange(len(q)):node=q.popleft()t+=node.valifnode.left:q.append(node.left)ifnode.right:q.append(node.right)ifs>t:s=tans=levellevel+=1returnans
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcminimumLevel(root*TreeNode)(ansint){q:=[]*TreeNode{root}s:=math.MaxInt64forlevel:=1;len(q)>0;level++{t:=0form:=len(q);m>0;m--{node:=q[0]q=q[1:]t+=node.Valifnode.Left!=nil{q=append(q,node.Left)}ifnode.Right!=nil{q=append(q,node.Right)}}ifs>t{s=tans=level}}return}