Sum of Nodes at a Specific Depth in a Binary Tree - aloalgo

Sum of Nodes at a Specific Depth in a Binary Tree

Medium

You are given the root of a binary tree and an integer depth.

Your task is to compute the sum of all node values located at the specified depth.

Note that:

  • The root node is defined to be at depth 0.
  • The depth of a node increases by 1 for each level down from its parent.

Return the total sum of node values at the given depth. If no nodes are found at the specified depth, return 0.

Example 1

Inputs
3920157
depth = 2
Output
22
Explanation:

At depth 2, the nodes are 15 and 7. Their sum is 15 + 7 = 22.

Example 2

Inputs
123
depth = 2
Output
3
Explanation:

The tree is 1 -> null -> 2 -> null -> 3. At depth 2, only node 3 exists. Its value is 3.

Example 3

Inputs
1
depth = 0
Output
1
Explanation:

At depth 0, the only node is the root with value 1. Its sum is 1.

Loading...
Inputs
3920157
depth = 2
Output
22

Hello! I am your ✨ AI assistant. I can provide you hints, explanations, give feedback on your code, and more. Just ask me anything related to the problem you're working on!