Skip to main content

Binary Tree Node Depth Sum

easy
Binary TreeBreadth First SearchTreeDepth First SearchBfs Level OrderDfs Recursive
Asked atAmazonGoogleMicrosoft

Problem Description

Given the root of a binary tree, return the sum of every node's value multiplied by its depth.

The root node is at depth **1**, its children are at depth **2**, and so on.

**Example 1:**
```
Input: root = [3, 7, 2, null, null, 4, 6]
Output: 3*1 + 7*2 + 2*2 + 4*3 + 6*3 = 3 + 14 + 4 + 12 + 18 = 51
```

**Example 2:**
```
Input: root = [5, 3, null]
Output: 5*1 + 3*2 = 5 + 6 = 11
```

**Constraints:**
- The number of nodes in the tree is in the range `[1, 1000]`.
- `-100 <= Node.val <= 100`

Constraints

  • 1 <= number of nodes <= 1000
  • -100 <= Node.val <= 100

Follow-up

What if you wanted to weight by the node's distance from the **deepest** leaf instead of its distance from the root?

Hints

Try the problem first. If you get stuck, you can reveal hints one at a time.

Solution

Leaderboard

No entries yet for python.

Be the first — submit an accepted solution.