Facebook Pixel

3157. Find the Level of Tree with Minimum Sum 🔒


Problem Description

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 plus one.

Intuition

The goal is to find the level in a binary tree that has the minimum sum of node values. To solve this, we use a Breadth-First Search (BFS) approach. By traversing the tree level by level, we can calculate the sum of node values for each level and keep track of the level with the smallest sum. The BFS approach leverages a queue to manage the nodes at each level, ensuring that all nodes on the same level are processed together before moving to the next level. This method naturally keeps track of which level is being processed, allowing us to compare sums efficiently and return the desired level.

Learn more about Tree, Depth-First Search, Breadth-First Search and Binary Tree patterns.

Solution Approach

To find the level with the minimum sum of node values in a binary tree, we use the Breadth-First Search (BFS) algorithm. BFS is ideal for this task because it processes the tree level by level, allowing us to compute and compare the sum of each level efficiently. Here's how the algorithm is implemented:

  1. Initialize a Queue: Use a deque to hold nodes. Start by adding the root node to the queue.

  2. Setup Variables:

    • level keeps track of the current level number, starting at 1 for the root.
    • ans will store the level with the minimum sum.
    • s is initialized to infinity and will record the smallest sum observed.
  3. Iterate Over Each Level:

    • While the queue is not empty, begin processing one level at a time.
    • Compute the number of nodes at the current level using len(q).
  4. Sum Level Values:

    • Initialize a temporary sum t for the current level.
    • Dequeue each node at the current level, adding its value to t.
    • If the node has left or right children, enqueue these children for processing at the next level.
  5. Update Minimum Check:

    • Compare the sum t of the current level with the smallest sum so far s.
    • If t is less than s, update s to t and record the current level in ans.
  6. Move to Next Level: Increment the level counter to proceed to the next level in the subsequent iterations.

  7. Return Result: After processing all levels, return ans, which now holds the level number with the minimum sum.

This BFS solution ensures that each level's sum is calculated in an orderly manner, and each node is processed exactly once, resulting in an efficient O(n) time complexity, where n is the number of nodes in the tree.

Ready to land your dream job?

Unlock your dream job with a 2-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Consider a binary tree with the following structure:

      1
     / \
    2   3
   /|   |
  4 5   6
        |
        7
  • Level 1 has just one node: [1]. The sum is 1.
  • Level 2 includes nodes: [2, 3]. The sum is 2 + 3 = 5.
  • Level 3 includes nodes: [4, 5, 6]. The sum is 4 + 5 + 6 = 15.
  • Level 4 has a single node: [7]. The sum is 7.

Initially, set ans = 1 and s = infinity to represent no minimum level found yet. Let's apply the BFS solution:

  1. Initialize Queue:

    • Start with the root node in the queue: q = [1].
  2. Level 1 Calculation:

    • Process node 1, sum for this level t = 1.
    • Update s and ans since 1 < infinity. Now, s = 1 and ans = 1.
    • Enqueue children [2, 3] for the next level.
  3. Level 2 Calculation:

    • Nodes 2 and 3 are dequeued from q.
    • Sum for this level t = 2 + 3 = 5.
    • Since 5 is not less than 1, no update to s or ans.
    • Enqueue children [4, 5, 6] for the next level.
  4. Level 3 Calculation:

    • Nodes 4, 5, 6 are dequeued from q.
    • Sum for this level t = 4 + 5 + 6 = 15.
    • Since 15 is not less than 1, no update to s or ans.
    • Enqueue child [7] for the next level.
  5. Level 4 Calculation:

    • Node 7 is dequeued from q.
    • Sum for this level t = 7.
    • Since 7 is not less than 1, no update to s or ans.

All levels are processed. Result: Return the value of ans, which is 1, indicating the level with the minimum sum is level 1.

Solution Implementation

1from collections import deque
2from typing import Optional
3
4# Definition for a binary tree node.
5class TreeNode:
6    def __init__(self, val=0, left=None, right=None):
7        self.val = val
8        self.left = left
9        self.right = right
10
11class Solution:
12    def minimumLevel(self, root: Optional[TreeNode]) -> int:
13        # Initialize a queue for breadth-first search, starting with the root node.
14        q = deque([root])
15      
16        # Variable to store the answer, which is the minimum level with the smallest sum.
17        ans = 0
18      
19        # Initialize the level and the smallest sum found so far.
20        level, smallest_sum = 1, float('inf')
21      
22        while q:
23            # Variable to store the sum of node values at the current level.
24            level_sum = 0
25          
26            # Iterate through the nodes at the current level.
27            for _ in range(len(q)):
28                node = q.popleft()
29              
30                # Add the current node's value to the level sum.
31                level_sum += node.val
32              
33                # Append the left child to the queue if it exists.
34                if node.left:
35                    q.append(node.left)
36              
37                # Append the right child to the queue if it exists.
38                if node.right:
39                    q.append(node.right)
40          
41            # Update the smallest sum and the answer if the current level sum is smaller.
42            if smallest_sum > level_sum:
43                smallest_sum = level_sum
44                ans = level
45          
46            # Move to the next level.
47            level += 1
48      
49        # Return the level with the smallest sum of node values.
50        return ans
51
1/**
2 * Definition for a binary tree node.
3 */
4public class TreeNode {
5    int val;
6    TreeNode left;
7    TreeNode right;
8  
9    TreeNode() {}
10
11    TreeNode(int val) {
12        this.val = val;
13    }
14
15    TreeNode(int val, TreeNode left, TreeNode right) {
16        this.val = val;
17        this.left = left;
18        this.right = right;
19    }
20}
21
22class Solution {
23    public int minimumLevel(TreeNode root) {
24        // Initialize a queue to perform level order traversal
25        Deque<TreeNode> queue = new ArrayDeque<>();
26        queue.offer(root);
27
28        int minLevel = 0;
29        long minSum = Long.MAX_VALUE;
30
31        // Perform BFS to traverse each level of the tree
32        for (int currentLevel = 1; !queue.isEmpty(); ++currentLevel) {
33            long currentSum = 0;
34            int nodesAtCurrentLevel = queue.size();
35
36            // Process all nodes at the current level
37            for (int i = 0; i < nodesAtCurrentLevel; ++i) {
38                TreeNode node = queue.poll();
39                currentSum += node.val;
40
41                // Add left and right children to the queue if they exist
42                if (node.left != null) {
43                    queue.offer(node.left);
44                }
45                if (node.right != null) {
46                    queue.offer(node.right);
47                }
48            }
49
50            // Update minimum sum and level if current level sum is smaller
51            if (currentSum < minSum) {
52                minSum = currentSum;
53                minLevel = currentLevel;
54            }
55        }
56
57        return minLevel; // Return the level with the minimum sum
58    }
59}
60
1#include <queue>
2#include <climits>
3
4// Definition for a binary tree node.
5struct TreeNode {
6    int val;                      // Value of the node
7    TreeNode* left;               // Pointer to the left child
8    TreeNode* right;              // Pointer to the right child
9    TreeNode() : val(0), left(nullptr), right(nullptr) {}                         // Default constructor
10    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}                    // Constructor with value
11    TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {} // Constructor with value, left and right child
12};
13
14class Solution {
15public:
16    int minimumLevel(TreeNode* root) {
17        if (!root) return 0; // If the root is null, return 0 as there are no levels
18
19        std::queue<TreeNode*> nodeQueue; // Queue to perform level-order traversal
20        nodeQueue.push(root);            // Start with the root node
21
22        int ans = 0;                      // To store the level with the minimum sum
23        long long minSum = LLONG_MAX;     // Initialize minSum with a large value (maximum possible long long value)
24
25        for (int level = 1; !nodeQueue.empty(); ++level) {
26            long long levelSum = 0; // To store the sum of values at the current level
27            int count = nodeQueue.size(); // Number of nodes in the current level
28
29            // Iterate over all nodes in the current level
30            for (int i = 0; i < count; ++i) {
31                TreeNode* node = nodeQueue.front();
32                nodeQueue.pop();
33                levelSum += node->val;   // Add the node's value to the level's sum
34
35                // Push the left and right children to the queue if they exist
36                if (node->left) {
37                    nodeQueue.push(node->left);
38                }
39                if (node->right) {
40                    nodeQueue.push(node->right);
41                }
42            }
43
44            // If the current level's sum is less than the recorded minimum sum, update it
45            if (levelSum < minSum) {
46                minSum = levelSum;
47                ans = level;
48            }
49        }
50
51        return ans; // Return the level which has the minimum sum
52    }
53};
54
1// TypeScript function to find the level with the minimum sum in a binary tree.
2// The TreeNode interface represents a node in a binary tree.
3interface TreeNode {
4    val: number;
5    left: TreeNode | null;
6    right: TreeNode | null;
7}
8
9// Function to determine the level with the smallest sum of values in the binary tree.
10function minimumLevel(root: TreeNode | null): number {
11    // Initialize a queue with the root node for level order traversal.
12    const q: TreeNode[] = [root];
13    // Initialize the smallest sum seen so far to Infinity, and the answer to level 0.
14    let s = Infinity;
15    let ans = 0;
16
17    // Traverse level by level until the queue is empty.
18    for (let level = 1; q.length; ++level) {
19        const qq: TreeNode[] = []; // Temporary queue for the next level.
20        let t = 0; // Sum of the current level.
21
22        // Traverse nodes of the current level.
23        for (const { val, left, right } of q) {
24            t += val; // Add the value of the current node to the sum of the level.
25            left && qq.push(left);  // If there is a left child, add it to the next level queue.
26            right && qq.push(right); // If there is a right child, add it to the next level queue.
27        }
28
29        // If the current level sum is less than the smallest sum recorded, update the smallest sum and answer.
30        if (s > t) {
31            s = t;
32            ans = level;
33        }
34
35        // Replace the current queue with the next level queue.
36        q.splice(0, q.length, ...qq);
37    }
38
39    // Return the level with the minimum sum.
40    return ans;
41}
42

Time and Space Complexity

The time complexity of the code is O(n), where n is the number of nodes in the binary tree. This is because each node is processed exactly once during the breadth-first traversal of the tree.

The space complexity of the code is O(n), which is allocated for storing the nodes at the current level in the queue q. In the worst case, the queue might store up to the maximum number of nodes at any level of the tree, which can be proportional to n for a balanced tree.

Learn more about how to find time and space complexity quickly.


Discover Your Strengths and Weaknesses: Take Our 2-Minute Quiz to Tailor Your Study Plan:
Question 1 out of 10

Which data structure is used in a depth first search?


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!


Load More