BackeasyTrees

Odd Depth Leaf Sum Solution

Problem Statement

Given the root of a binary tree, calculate the sum of all leaf nodes that are located at an odd depth. The root node is considered to be at depth 1, its immediate children are at depth 2, their children are at depth 3, and so forth. A leaf node is defined as a node with no children.

Example 1
Input
root = [1, 2, 3, 4, null, null, 5]
Output
9

Explanation: The leaf nodes in this tree are 4 and 5. Node 4 is at depth 3 (odd) and Node 5 is at depth 3 (odd). The sum of these odd-depth leaf nodes is 4 + 5 = 9.

Example 2
Input
root = [1, 2, null]
Output
0

Explanation: The only leaf node is 2, which is at depth 2 (even). Since there are no leaf nodes at odd depths, the sum is 0.

Constraints

  • The number of nodes in the tree is in the range [0, 5000].
  • -1000 <= Node.val <= 1000
  • The maximum depth of the tree is at most 1000.
Live Compiler
Loading...
Test Cases & Output
🔒 Sign up to run your code

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free