Count subtrees with Sum equal to target in binary tree

Previous
Next

In this post, we will see about how to count subtrees with Sum equal to target in binary tree

Problem

Given a Binary tree and an integer. You need to find the number of subtrees having the sum of all of its nodes equal to given Integer, that is, Target sum.


Solution

For solving this problem, we calculate the result in postorder while returning from recursion in which we return a Pair object which contains the sum of current subtree and count of subtrees having their sum equal to given sum.

So basically, we keep on recurring to child of the current node until we finally reach to a null node where we return an empty pair class object in which sum of current subtree is zero and also the count of subtrees with sum equal to target sum equal to zero.
Result of any node or the pair to be returned will be calculated using the pair objects returned from left child and right child of the current node.
There are two things we need to calculate for current node :

  • (i)┬áSUM : Sum of current node will be the summation of left subtree sum, right subtree sum and value of
    current node.
  • (ii) Count : Count of subtrees with sum Equal to target sum will left count + right count and add one if the
    overall sum of the current node is equal to target sum.

The time complexity of this algorithm would be similar to all other traversals like postorder, that is, O(n) , where ‘n’ is number of nodes in the tree.

Binary tree

That’s all about Count subtrees with Sum equal to target in binary tree.

Latest posts by Ayush Kumar (see all)

Previous
Next

Join Our News Letter – Stay Updated

Subscribe to Awesome Java Content.




Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog