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>usingnamespacestd;// Definition for a binary tree node.structTreeNode{intval;TreeNode*left;TreeNode*right;TreeNode(intx):val(x),left(NULL),right(NULL){}};// Helper function to create a new tree nodeTreeNode*newNode(intval){TreeNode*node=newTreeNode(val);node->left=node->right=NULL;returnnode;}intcountNodes(TreeNode*root){// Initialize counterintcount=0;// Start the recursive processsumSubtree(root,count);// Return the final countreturncount;}// Recursive function to compute the sum of a subtreeintsumSubtree(TreeNode*node,int&count){// Base case: if the node is null, return 0if(node==NULL)return0;// Recursive case: compute the sum of left and right// subtreesintleftSum=sumSubtree(node->left,count);intrightSum=sumSubtree(node->right,count);// The sum of descendants is the sum of left and right// subtree sumsinttotalSum=leftSum+rightSum;// Check if the current node's value matches the sum of// its descendantsif(node->val==totalSum){// Increment the counter if the condition is metcount++;}// Return the sum of the current node and its// descendantsreturnnode->val+totalSum;}// Driver codeintmain(){// Creating a sample binary treeTreeNode*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;return0;}
Java
// Definition for a binary tree node.classTreeNode{intval;TreeNodeleft;TreeNoderight;TreeNode(intx){val=x;left=right=null;}}publicclassBinaryTree{// Helper function to create a new tree nodepublicstaticTreeNodenewNode(intval){TreeNodenode=newTreeNode(val);node.left=node.right=null;returnnode;}publicstaticintcountNodes(TreeNoderoot){// Initialize counterint[]count={0};// Start the recursive processsumSubtree(root,count);// Return the final countreturncount[0];}// Recursive function to compute the sum of a subtreepublicstaticintsumSubtree(TreeNodenode,int[]count){// Base case: if the node is null, return 0if(node==null){return0;}// Recursive case: compute the sum of left and right// subtreesintleftSum=sumSubtree(node.left,count);intrightSum=sumSubtree(node.right,count);// The sum of descendants is the sum of left and// right subtree sumsinttotalSum=leftSum+rightSum;// Check if the current node's value matches the sum// of its descendants and it has at least one childif(node.val==totalSum&&(node.left!=null||node.right!=null)){// Increment the counter if the condition is metcount[0]++;}// Return the sum of the current node and its// descendantsreturnnode.val+totalSum;}publicstaticvoidmain(String[]args){// Creating a sample binary treeTreeNoderoot=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
Output
Number 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).