1302. Deepest Leaves Sum LeetCode Solution

In this guide, you will get 1302. Deepest Leaves Sum LeetCode Solution with the best time and space complexity. The solution to Deepest Leaves Sum problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Deepest Leaves Sum solution in C++
  4. Deepest Leaves Sum solution in Java
  5. Deepest Leaves Sum solution in Python
  6. Additional Resources
1302. Deepest Leaves Sum LeetCode Solution image

Problem Statement of Deepest Leaves Sum

Given the root of a binary tree, return the sum of values of its deepest leaves.

Example 1:

Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
Output: 15

Example 2:

Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
Output: 19

Constraints:

The number of nodes in the tree is in the range [1, 104].
1 <= Node.val <= 100

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(n)

1302. Deepest Leaves Sum LeetCode Solution in C++

class Solution {
 public:
  int deepestLeavesSum(TreeNode* root) {
    int ans = 0;
    queue<TreeNode*> q{{root}};

    while (!q.empty()) {
      ans = 0;
      for (int sz = q.size(); sz > 0; --sz) {
        TreeNode* node = q.front();
        q.pop();
        ans += node->val;
        if (node->left)
          q.push(node->left);
        if (node->right)
          q.push(node->right);
      }
    }

    return ans;
  }
};
/* code provided by PROGIEZ */

1302. Deepest Leaves Sum LeetCode Solution in Java

class Solution {
  public int deepestLeavesSum(TreeNode root) {
    int ans = 0;
    Queue<TreeNode> q = new ArrayDeque<>(List.of(root));

    while (!q.isEmpty()) {
      ans = 0;
      for (int sz = q.size(); sz > 0; --sz) {
        TreeNode node = q.poll();
        ans += node.val;
        if (node.left != null)
          q.offer(node.left);
        if (node.right != null)
          q.offer(node.right);
      }
    }

    return ans;
  }
}
// code provided by PROGIEZ

1302. Deepest Leaves Sum LeetCode Solution in Python

N/A
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.