Count subtrees with Sum equal to target in binary tree

If you want to practice data structure and algorithm programs, you can go through 100+ java coding interview questions.

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


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.


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.

Was this post helpful?


You may also like:

Related Posts

Leave a Reply

Your email address will not be published.

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.