FastPrepReplace Each Node with Its Descendant Sum
Problems/Replace Each Node with Its Descendant Sum

Replace Each Node with Its Descendant Sum

AMD logoAMD● MediumFULLTIMEONSITE INTERVIEW
QuestionFunctionExamplesConstraints

Problem statement

Source note: The source asks to add all child-node values and store the sum in their parent, without resolving immediate children versus all descendants. This exercise explicitly chooses strict descendants, original values and zero-valued leaves; bounds/interface are authored. Approximate source match70%.

For this practice interpretation, replace each node value with the sum of all its strict descendants original values. Exclude that node own original value. Descendants include children at every lower depth, not only immediate children. Leaves become0. Preserve the structure and return the root; input mutation is allowed.

Function

descendantSumTree(root: TreeNode) → TreeNode

Examples

Example 1

root = [10,-2,6,8,-4,7,5]return = [20,4,12,0,0,0,0]

The root receives-2+6+8-4+7+5=20. Its children receive8-4=4and7+5=12; all four leaves become0.

Example 2

root = [5]return = [0]

A single node has no strict descendants, so its replacement is0.

Constraints

  • 0 <= every serialized input tree length <= 400.
  • -1000 <= every non-null input node value <= 1000.
  • Every input is a valid acyclic binary tree serialized in level order with null missing children; [] denotes an empty tree.

More AMD problems

  • Insert After a Linked-List NodeONSITE INTERVIEW · Seen Oct 2026
  • LRU CacheONSITE INTERVIEW · Seen Oct 2026
  • Lowest Common Ancestor of a Binary TreePHONE SCREEN · Seen Oct 2026
All AMD interview questionsSee AMD hiring insights
Saved
public TreeNode descendantSumTree(TreeNode root) {
    // Write your code here.
}
Checking account…