Sobes.tech
Junior — Senior

Calculating the sum of leaf values at the deepest level of the tree

livecode

Task condition

Given a binary tree with the root node treeRoot. The task is to calculate the sum of values of all leaf nodes located at the maximum depth of the tree. A leaf node is considered a node that has no children. The depth of a node is defined as the number of edges from the root to that node.

Example 1: Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8] Output: 15 Explanation:

  • Tree: [1,2,3,4,5,null,6,7,null,null,null,null,8].
  • Maximum depth = 3 (nodes 7 and 8).
  • Leaf nodes at depth 3: 7 and 8.
  • Sum: 7 + 8 = 15.

Example 2: Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5] Output: 19 Explanation:

  • Tree: [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5].
  • Maximum depth = 4 (nodes 9, 1, 4, 5).
  • Leaf nodes at depth 4: 9, 1, 4, 5.
  • Sum: 9 + 1 + 4 + 5 = 19.