Last Updated: 3 Nov, 2025

Equal Subtree Sums

Easy
Asked in company
Josh Technology Group

Problem statement

You are given a binary tree where each node contains an integer value. Your task is to count the number of nodes in the tree that satisfy a specific property: the sum of all node values in the node's left subtree must be equal to the node's own value, AND the sum of all node values in its right subtree must also be equal to the node's own value.


Definitions:

The sum of an empty subtree (i.e., if a child is null) is considered to be 0.

A leaf node has a left subtree sum of 0 and a right subtree sum of 0.


Input Format:
The first line contains a single integer N, the number of nodes in the level-order representation of the tree.

The second line contains N space-separated integers, representing the tree in level-order format. A value of -1 indicates a null node.


Output Format:
Print a single integer representing the total count of nodes that satisfy the property.


Note:
To solve this efficiently, a single traversal of the tree is required. A post-order traversal (DFS) is ideal. A recursive function can calculate the sum of a subtree and, after receiving the sums from its children, perform the check for the current node.