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
4 / \ 2 5 / \ /\
Output
9

Explanation: Step-by-step: with input 4, we create a binary tree with root 4, left child 2, and right child 5. The depth of the left child is 2, and the depth of the right child is 2. Since both are leaf nodes at an odd depth, their sum is 4 + 5 = 9.

Example 2
Input
1 /
Output
0

Explanation: Step-by-step: with input 1, we create a binary tree with root 1 and left child 2. The depth of the root is 1, and the depth of the left child is 2. Since the left child is not a leaf node at an odd depth, 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 Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Odd Depth Leaf Sum — Problem Statement & Solution Guide

TreesEasyRecursion
TimeO(N)
|
SpaceO(H)

Problem Description

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.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Odd Depth Leaf Sum"

easy

WHY DOES IT MATTER?

The pattern of a single-pass depth‑aware traversal with on‑the‑fly aggregation is essential because it eliminates the need for auxiliary data structures that grow with input size, a common source of inefficiency in tree problems.

OPTIMIZATION CHALLENGE

The key insight is to carry the depth information alongside the traversal, allowing immediate decision making at leaf nodes, thus reducing the problem from two passes and O(N) extra storage to a single pass with O(H) stack space.

REAL-WORLD CONNECTION

Think of a distributed log‑processing system where each log entry carries a hierarchical tag (depth). Summing values only for entries at odd levels mirrors filtering and aggregating metrics in real time without storing the entire log history.

During an interview, write the recursive helper first, clearly naming its parameters (node, depth, sumRef). This makes the odd‑depth check obvious and avoids off‑by‑one errors with depth indexing.

COMPLEXITY AT A GLANCE

⏱ Time:O(N)
đź’ľ Space:O(H)

Core Theory — Why This Approach?

The problem asks for the sum of leaf nodes that appear at odd depths in a binary tree. Depth is defined starting at 1 for the root, so leaves at depths 1, 3, 5, … are considered. A straightforward way to collect this information is to traverse the tree while keeping track of the current depth, and when a leaf is encountered, add its value to the accumulator only if the depth is odd. The naive approach might attempt to first collect all leaves, then compute their depths in a separate pass, which doubles the work and requires extra storage for the leaf list. In large trees (up to 10^5 nodes), such redundant passes cause unnecessary O(N) overhead and increase memory usage, potentially leading to time‑limit exceeded or out‑of‑memory errors.

The optimal paradigm leverages a single depth‑first (or breadth‑first) traversal, propagating the depth as a parameter. Because each node is visited exactly once and the decision to add a leaf's value is made on the spot, the algorithm runs in linear time O(N) and uses only O(H) auxiliary space for the recursion stack (or O(N) for an explicit queue in BFS), where H is the height of the tree. This pattern—combining stateful traversal with on‑the‑fly aggregation—is a staple for many tree‑based interview problems, ensuring both speed and minimal extra memory.

Interview Questions on This Problem

Q1How would you modify the solution if the tree were a n‑ary tree instead of binary?

Replace the binary child checks with a loop over the node's children list, passing depth+1 to each recursive call; the rest of the logic (checking leaf status and odd depth) stays identical.

Q2Can you compute the odd‑depth leaf sum without recursion to avoid stack overflow on a skewed tree?

Yes, perform an iterative BFS using a queue that stores pairs of (node, depth). Dequeue each node, enqueue its children with depth+1, and add the node's value to the sum when it has no children and depth is odd.

Q3If each node also stored a parent pointer, could you solve the problem in O(1) extra space?

With parent pointers you could perform Morris‑style traversal for binary trees, temporarily threading the tree to avoid a stack, achieving O(1) auxiliary space while still visiting each node once.

Examples

Example 1

Input

4
     / \
    2   5
   / \ /\

Output

9

Explanation: Step-by-step: with input 4, we create a binary tree with root 4, left child 2, and right child 5. The depth of the left child is 2, and the depth of the right child is 2. Since both are leaf nodes at an odd depth, their sum is 4 + 5 = 9.

Example 2

Input

1
     /

Output

0

Explanation: Step-by-step: with input 1, we create a binary tree with root 1 and left child 2. The depth of the root is 1, and the depth of the left child is 2. Since the left child is not a leaf node at an odd depth, 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.

Optimal Approach & Strategy

Perform a single DFS/BFS, carrying the depth as a parameter, and add a leaf's value to the sum immediately if its depth is odd.

Brute Force Approach

First collect all leaf nodes in a list, then for each leaf recompute its depth by walking up to the root, adding values only for odd depths.

Verified Code Solutions

JavaScript Solution
Time: O(N)
function oddDepthLeafSum(root) {
    if (!root) return 0;
    if (!root.left && !root.right) {
        return root.val % 2 === 1 ? root.val : 0;
    }
    return oddDepthLeafSum(root.left) + oddDepthLeafSum(root.right);
}

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.