Count Number of Nodes Equal to Sum of Descendants
Last Updated :
14 Jun, 2024
Given the root of a binary tree. The task is to return the number of nodes where the value of the node is equal to the sum of the values of its descendants. A descendant of a node is any node that is on the path from the node to some leaf node. The sum is considered to be 0 if the node has no descendants.
Examples:
Input: root = [9,2,5,1,1]

Output: 2
Explanation:
- For the node with value 9: The sum of its descendants is 2+5+1+1 = 9.
- For the node with value 2: The sum of its descendants is 1+1 = 3.
Input: root = [2,4,null,3,1]

Output: 1
Approach:
The key idea is to traverse the tree and compute the sum of all values in the subtree rooted at each node. By using a depth-first search (DFS) traversal, we can calculate these sums as we traverse. For each node, we recursively calculate the sum of the left subtree and the right subtree. The sum of the current node's descendants is the sum of these two subtree sums. If the current node's value equals this computed sum of its descendants, we increment our count. To implement this, we define a helper function that not only computes the sum of a subtree but also updates a counter whenever a node's value matches the sum of its descendants.
Step-by-step approach:
- Create a countNodes() function that takes the root of the binary tree as input:
- Initialize a counter variable count to 0.
- Call the recursive helper function sumSubtree() with the root node and the count reference as arguments.
- Return the final value of the count variable.
- Create a sumSubtree() function that takes a node and a reference to the count variable as input.
- If the current node is NULL, return 0 (base case).
- Recursively compute the sum of the left and right subtrees by calling sumSubtree on the left and right child nodes.
- Check if the current node's value is equal to the sum of its left and right subtree sums.
- If the condition is met, increment the count variable.
- Return the sum of the current node's value and the sums of its left and right subtrees.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x)
: val(x)
, left(NULL)
, right(NULL)
{
}
};
// Helper function to create a new tree node
TreeNode* newNode(int val)
{
TreeNode* node = new TreeNode(val);
node->left = node->right = NULL;
return node;
}
int countNodes(TreeNode* root)
{
// Initialize counter
int count = 0;
// Start the recursive process
sumSubtree(root, count);
// Return the final count
return count;
}
// Recursive function to compute the sum of a subtree
int sumSubtree(TreeNode* node, int& count)
{
// Base case: if the node is null, return 0
if (node == NULL)
return 0;
// Recursive case: compute the sum of left and right
// subtrees
int leftSum = sumSubtree(node->left, count);
int rightSum = sumSubtree(node->right, count);
// The sum of descendants is the sum of left and right
// subtree sums
int totalSum = leftSum + rightSum;
// Check if the current node's value matches the sum of
// its descendants
if (node->val == totalSum) {
// Increment the counter if the condition is met
count++;
}
// Return the sum of the current node and its
// descendants
return node->val + totalSum;
}
// Driver code
int main()
{
// Creating a sample binary tree
TreeNode* root = newNode(10);
root->left = newNode(3);
root->right = newNode(7);
root->left->left = newNode(3);
root->left->right = newNode(0);
root->right->left = newNode(2);
root->right->right = newNode(5);
cout << "Number of nodes where value is equal to sum "
"of descendants: "
<< countNodes(root) << endl;
return 0;
}
Java
// Definition for a binary tree node.
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x)
{
val = x;
left = right = null;
}
}
public class BinaryTree {
// Helper function to create a new tree node
public static TreeNode newNode(int val)
{
TreeNode node = new TreeNode(val);
node.left = node.right = null;
return node;
}
public static int countNodes(TreeNode root)
{
// Initialize counter
int[] count = { 0 };
// Start the recursive process
sumSubtree(root, count);
// Return the final count
return count[0];
}
// Recursive function to compute the sum of a subtree
public static int sumSubtree(TreeNode node, int[] count)
{
// Base case: if the node is null, return 0
if (node == null) {
return 0;
}
// Recursive case: compute the sum of left and right
// subtrees
int leftSum = sumSubtree(node.left, count);
int rightSum = sumSubtree(node.right, count);
// The sum of descendants is the sum of left and
// right subtree sums
int totalSum = leftSum + rightSum;
// Check if the current node's value matches the sum
// of its descendants and it has at least one child
if (node.val == totalSum
&& (node.left != null || node.right != null)) {
// Increment the counter if the condition is met
count[0]++;
}
// Return the sum of the current node and its
// descendants
return node.val + totalSum;
}
public static void main(String[] args)
{
// Creating a sample binary tree
TreeNode root = newNode(10);
root.left = newNode(3);
root.right = newNode(7);
root.left.left = newNode(3);
root.left.right = newNode(0);
root.right.left = newNode(2);
root.right.right = newNode(5);
System.out.println(
"Number of nodes where value is equal to sum of descendants: "
+ countNodes(root));
}
}
// This code is contributed by Shivam Gupta
OutputNumber of nodes where value is equal to sum of descendants: 2
Time complexity: O(N), where N is the number of nodes in the tree. Each node is visited exactly once during the traversal.
Auxiliary Space: O(H), where H is the height of the tree. This space is used by the call stack due to recursion. In the worst case (for a skewed tree), H can be equal to N. For a balanced tree, O(logN).