Show problems as
Classic problem #404EasyTreeDepth-First SearchBreadth-First SearchBinary Tree

Sum of Left Leaves

Real-world version: Weights on the Tips of First Slots
Tracked in this browser only
Read Sum of Left Leaves on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A mobile hangs from a single top weight. Every weight holds at most two weights below it in a first and a second slot, and either slot may be empty. Each weight shows a number.

A flat list is read level by level: its first entry is the top weight's number, and reading left to right, every entry that is not null claims the next two unused positions as its first and second slot in that order, while null marks an empty slot and claims no positions of its own.

A weight is a tip when both of its slots are empty. Return the total of the numbers on the tips that hang in a first slot.

Examples

Example 1

Input
mobile = [1, 2, 3, 4, 5, 6, 7]
Output
10

The four weights at the bottom are the tips. Two of them hang in a first slot, showing 4 and 6, so the total is 10.

Example 2

Input
mobile = [1, null, 2]
Output
0

The one weight below the top hangs in a second slot, so nothing counts.

Example 3

Input
mobile = [1, 2]
Output
2

The single weight below the top hangs in a first slot with nothing under it.

Constraints

  • 1 <= mobile.length <= 2000
  • The mobile holds between 1 and 1000 weights.
  • -1000 <= mobile[i] <= 1000
  • The first entry of the list is not null.

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def sum_of_left_leaves(mobile: list) -> int:
Java
public int sumOfLeftLeaves(Integer[] mobile)