Subtree with given sum in a Binary Tree

Last Updated : 15 Jan, 2026

You are given a binary tree and a given sum. The task is to check if there exists a subtree whose sum of all nodes is equal to the given sum.

Examples:

Input : key = 11

ex-3


Output: True
Explanation: sum of all nodes of subtree {2, 4, 5} = 11.

Input : key = 6

ex-3

Output: False
Explanation: No subtree whose sum of all nodes = 6.

[Approach] Using Recursion - O(n) Time and O(h) Space

The idea is to traverse the binary tree recursively, calculating the sum of the subtree rooted at each node. At each node, we compute the sum of its left and right subtrees and add the node's value itself. If the sum of any subtree matches the given key sum, we mark it as found. We use a helper function subtreeSum() to compute the sum of each subtree and a flag foundSum to track if the key sum is found.

Below is the implementation of the above approach: 

C++
// C++ program to find if there is a subtree with
// given sum

#include <iostream>
using namespace std;

class Node {
public:
    int data;
    Node* left;
    Node* right;

    Node(int x) {
        data = x;
        left = nullptr;
        right = nullptr;
    }
};

// Function to calculate the sum of the subtree rooted at the given node
int subtreeSum(Node* root, int& foundSum, int target) {
  
    // Base case: If the node is NULL, return 0
    if (root == nullptr)
        return 0;

    // Calculate the sum of the current subtree
    int currentSum = root->data + 
                    subtreeSum(root->left, foundSum, target) + 
                    subtreeSum(root->right, foundSum, target);

    // If the current subtree sum matches the target, 
    // set foundSum to 1
    if (currentSum == target) {
        foundSum = 1;
    }

    // Return the current subtree sum
    return currentSum;
}

// Function to check if there is a subtree with the given sum
bool hasSubtreeWithGivenSum(Node* root, int sum) {
    int foundSum = 0;

    // Traverse the tree and check for the target sum
    subtreeSum(root, foundSum, sum);

    // Return true if a subtree with the given sum was found
    return foundSum == 1;
}

int main() {
  
    // Creating the given binary tree
    //        1
    //       / \
    //      3   6
    //     / \   /
    //    5   9 8

    Node* root = new Node(1);
    root->left = new Node(3);
    root->right = new Node(6);
    root->left->left = new Node(5);
    root->left->right = new Node(9);
    root->right->left = new Node(8);

    if(hasSubtreeWithGivenSum(root, 17)) {
      cout << "True";
    }
  	else cout << "False";
    return 0;
}
C
// C program to find if there is a subtree with
// given sum

#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node* left;
    struct Node* right;
};

// Function to calculate the sum of the subtree rooted at the given node
int subtreeSum(struct Node* root, int* foundSum, int target) {
  
    // Base case: If the node is NULL, return 0
    if (root == NULL)
        return 0;

    // Calculate the sum of the current subtree
    int currentSum = root->data + 
                    subtreeSum(root->left, foundSum, target) + 
                    subtreeSum(root->right, foundSum, target);

    // If the current subtree sum matches the target, 
    // set foundSum to 1
    if (currentSum == target) {
        *foundSum = 1;
    }

    // Return the current subtree sum
    return currentSum;
}

// Function to check if there is a subtree with the given sum
int hasSubtreeWithGivenSum(struct Node* root, int sum) {
    int foundSum = 0;

    // Traverse the tree and check for the target sum
    subtreeSum(root, &foundSum, sum);

    // Return true if a subtree with the given sum was found
    return foundSum == 1;
}

struct Node* createNode(int x) {
    struct Node* newNode = 
      (struct Node*)malloc(sizeof(struct Node));
    newNode->data = x;
    newNode->left = NULL;
    newNode->right = NULL;
    return newNode;
}

int main() {
  
    // Creating the given binary tree
    //        1
    //       / \
    //      3   6
    //     / \   /
    //    5   9 8

    struct Node* root = createNode(1);
    root->left = createNode(3);
    root->right = createNode(6);
    root->left->left = createNode(5);
    root->left->right = createNode(9);
    root->right->left = createNode(8);

    
    if(hasSubtreeWithGivenSum(root, 17)) {
      	printf("True");
    }
  	else printf("False");

    return 0;
}
Java
// Java program to find if there is a subtree with
// given sum

class Node {
    int data;
    Node left, right;

    Node(int x) {
        data = x;
        left = right = null;
    }
}

class GfG {

    // Function to calculate the sum of the subtree 
  	// rooted at the given node
    static int subtreeSum(Node root, boolean[] foundSum, int target) {
      
        // Base case: If the node is NULL, return 0
        if (root == null)
            return 0;

        // Calculate the sum of the current subtree
        int currentSum = root.data + 
                        subtreeSum(root.left, foundSum, target) + 
                        subtreeSum(root.right, foundSum, target);

        // If the current subtree sum matches the target, 
        // set foundSum to true
        if (currentSum == target) {
            foundSum[0] = true;
        }

        // Return the current subtree sum
        return currentSum;
    }

    // Function to check if there is a subtree with the given sum
    static boolean hasSubtreeWithGivenSum(Node root, int sum) {
        boolean[] foundSum = new boolean[1];

        // Traverse the tree and check for the target sum
        subtreeSum(root, foundSum, sum);

        // Return true if a subtree with the given sum was found
        return foundSum[0];
    }

    public static void main(String[] args) {
      
        // Creating the given binary tree
        //        1
        //       / \
        //      3   6
        //     / \   /
        //    5   9 8

        Node root = new Node(1);
        root.left = new Node(3);
        root.right = new Node(6);
        root.left.left = new Node(5);
        root.left.right = new Node(9);
        root.right.left = new Node(8);

        System.out.println(hasSubtreeWithGivenSum(root, 17));
    }
}
Python
# Python program to find if there is a subtree with
# given sum

# Node definition for a binary tree
class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None

# Function to calculate the sum of the subtree 
# rooted at the given node
def subtreeSum(root, foundSum, target):
  
    # Base case: If the node is NULL, return 0
    if root is None:
        return 0

    # Calculate the sum of the current subtree
    currentSum = (root.data +
                  subtreeSum(root.left, foundSum, target) +
                  subtreeSum(root.right, foundSum, target))

    # If the current subtree sum matches the target,
    # set foundSum to True
    if currentSum == target:
        foundSum[0] = True

    # Return the current subtree sum
    return currentSum

# Function to check if there is a subtree with the given sum
def hasSubtreeWithGivenSum(root, sum):
    foundSum = [False]

    # Traverse the tree and check for the target sum
    subtreeSum(root, foundSum, sum)

    # Return true if a subtree with the given sum was found
    return foundSum[0]

if __name__ == "__main__":
  
    # Creating the given binary tree
    #        1
    #       / \
    #      3   6
    #     / \   /
    #    5   9 8

    root = Node(1)
    root.left = Node(3)
    root.right = Node(6)
    root.left.left = Node(5)
    root.left.right = Node(9)
    root.right.left = Node(8)

    print(hasSubtreeWithGivenSum(root, 17))
C#
// C# program to find if there is a subtree with
// given sum

using System;

class Node {
    public int data;
    public Node left, right;

    public Node(int x) {
        data = x;
        left = right = null;
    }
}

class GfG {

    // Function to calculate the sum of the subtree 
  	// rooted at the given node
    static int SubtreeSum(Node root, ref bool foundSum, int target) {
      
        // Base case: If the node is NULL, return 0
        if (root == null)
            return 0;

        // Calculate the sum of the current subtree
        int currentSum = root.data + 
                        SubtreeSum(root.left, ref foundSum, target) + 
                        SubtreeSum(root.right, ref foundSum, target);

        // If the current subtree sum matches the target, 
        // set foundSum to true
        if (currentSum == target) {
            foundSum = true;
        }

        // Return the current subtree sum
        return currentSum;
    }

    // Function to check if there is a subtree with the given sum
    static bool HasSubtreeWithGivenSum(Node root, int sum) {
        bool foundSum = false;

        // Traverse the tree and check for the target sum
        SubtreeSum(root, ref foundSum, sum);

        // Return true if a subtree with the given sum was found
        return foundSum;
    }

    static void Main(string[] args) {
      
        // Creating the given binary tree
        //        1
        //       / \
        //      3   6
        //     / \   /
        //    5   9 8

        Node root = new Node(1);
        root.left = new Node(3);
        root.right = new Node(6);
        root.left.left = new Node(5);
        root.left.right = new Node(9);
        root.right.left = new Node(8);

        Console.WriteLine(HasSubtreeWithGivenSum(root, 17));
    }
}
JavaScript
// JavaScript program to find if there is a subtree with
// given sum

// Node definition for a binary tree
class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}

// Function to calculate the sum of the subtree 
// rooted at the given node
function subtreeSum(root, foundSum, target) {

    // Base case: If the node is NULL, return 0
    if (root === null)
        return 0;

    // Calculate the sum of the current subtree
    let currentSum = root.data + 
                    subtreeSum(root.left, foundSum, target) + 
                    subtreeSum(root.right, foundSum, target);

    // If the current subtree sum matches the target, 
    // set foundSum to true
    if (currentSum === target) {
        foundSum.value = true;
    }

    // Return the current subtree sum
    return currentSum;
}

// Function to check if there is a subtree with the given sum
function hasSubtreeWithGivenSum(root, sum) {
    let foundSum = { value: false };

    // Traverse the tree and check for the target sum
    subtreeSum(root, foundSum, sum);

    // Return true if a subtree with the given sum was found
    return foundSum.value;
}

// Creating the given binary tree
//        1
//       / \
//      3   6
//     / \   /
//    5   9 8

let root = new Node(1);
root.left = new Node(3);
root.right = new Node(6);
root.left.left = new Node(5);
root.left.right = new Node(9);
root.right.left = new Node(8);

console.log(hasSubtreeWithGivenSum(root, 17));

Output
True

Time Complexity: O(n), As we are visiting every node once.
Auxiliary space: O(h), here h is the height of the tree and the extra space is used due to the recursion call stack.

Comment