FastPrepCousins in Binary Tree II
Problems/Cousins in Binary Tree II

Cousins in Binary Tree II

Amazon logoAmazon● MediumNEW GRADONSITE INTERVIEW
QuestionFunctionExamples

Problem statement

Source note: The judged task matches the named standard cousin-sum replacement problem at about 99%. The statement supplies a portable level-order interface.

You are given a non-empty binary tree serialized as a level-order string array levelOrder. Each non-null token is a decimal integer, and "null" denotes a missing child.

Replace every node's value with the sum of the original values of all its cousins. Two nodes are cousins when they are at the same depth and have different parents. If a node has no cousins, its replacement value is 0.

All replacements are conceptually simultaneous. Return the updated tree using the same level-order array shape, preserving every "null" marker from the input.

Function

replaceValueInTree(levelOrder: String[]) → String[]

Examples

Example 1

levelOrder = ["5","4","9","1","10","null","7"]return = ["0","0","0","7","7","null","11"]

At depth 2, nodes 1 and 10 are siblings, so their only cousin has value 7. Node 7 has cousins with original values 1 and 10, whose sum is 11.

Example 2

levelOrder = ["3","1","2"]return = ["0","0","0"]

The root has no cousins, and the two nodes at depth 1 are siblings, so every replacement is 0.

Example 3

levelOrder = ["1","2","3","4","null","5","6"]return = ["0","0","0","11","null","4","4"]

At depth 2, node 4 receives 5 + 6 = 11, while sibling nodes 5 and 6 each receive the cousin value 4.

More Amazon problems

  • Count Adjacent Symbol Pairs for BPEONSITE INTERVIEW · Seen Nov 2026
  • First Non-Repeating CharacterOA · ONSITE INTERVIEW · Seen Nov 2026
  • Lowest Common Ancestor in an N-ary TreePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
See Amazon hiring insights
Saved
class Solution {
    public String[] replaceValueInTree(String[] levelOrder) {
      // write your code here
    }
}
Checking account…