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
Output: True Explanation: sum of all nodes of subtree {2, 4, 5} = 11.
Input : key = 6
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>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// Function to calculate the sum of the subtree rooted at the given nodeintsubtreeSum(Node*root,int&foundSum,inttarget){// Base case: If the node is NULL, return 0if(root==nullptr)return0;// Calculate the sum of the current subtreeintcurrentSum=root->data+subtreeSum(root->left,foundSum,target)+subtreeSum(root->right,foundSum,target);// If the current subtree sum matches the target, // set foundSum to 1if(currentSum==target){foundSum=1;}// Return the current subtree sumreturncurrentSum;}// Function to check if there is a subtree with the given sumboolhasSubtreeWithGivenSum(Node*root,intsum){intfoundSum=0;// Traverse the tree and check for the target sumsubtreeSum(root,foundSum,sum);// Return true if a subtree with the given sum was foundreturnfoundSum==1;}intmain(){// Creating the given binary tree// 1// / \ // 3 6// / \ /// 5 9 8Node*root=newNode(1);root->left=newNode(3);root->right=newNode(6);root->left->left=newNode(5);root->left->right=newNode(9);root->right->left=newNode(8);if(hasSubtreeWithGivenSum(root,17)){cout<<"True";}elsecout<<"False";return0;}
C
// C program to find if there is a subtree with// given sum#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*left;structNode*right;};// Function to calculate the sum of the subtree rooted at the given nodeintsubtreeSum(structNode*root,int*foundSum,inttarget){// Base case: If the node is NULL, return 0if(root==NULL)return0;// Calculate the sum of the current subtreeintcurrentSum=root->data+subtreeSum(root->left,foundSum,target)+subtreeSum(root->right,foundSum,target);// If the current subtree sum matches the target, // set foundSum to 1if(currentSum==target){*foundSum=1;}// Return the current subtree sumreturncurrentSum;}// Function to check if there is a subtree with the given suminthasSubtreeWithGivenSum(structNode*root,intsum){intfoundSum=0;// Traverse the tree and check for the target sumsubtreeSum(root,&foundSum,sum);// Return true if a subtree with the given sum was foundreturnfoundSum==1;}structNode*createNode(intx){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->data=x;newNode->left=NULL;newNode->right=NULL;returnnewNode;}intmain(){// Creating the given binary tree// 1// / \ // 3 6// / \ /// 5 9 8structNode*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");}elseprintf("False");return0;}
Java
// Java program to find if there is a subtree with// given sumclassNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}classGfG{// Function to calculate the sum of the subtree // rooted at the given nodestaticintsubtreeSum(Noderoot,boolean[]foundSum,inttarget){// Base case: If the node is NULL, return 0if(root==null)return0;// Calculate the sum of the current subtreeintcurrentSum=root.data+subtreeSum(root.left,foundSum,target)+subtreeSum(root.right,foundSum,target);// If the current subtree sum matches the target, // set foundSum to trueif(currentSum==target){foundSum[0]=true;}// Return the current subtree sumreturncurrentSum;}// Function to check if there is a subtree with the given sumstaticbooleanhasSubtreeWithGivenSum(Noderoot,intsum){boolean[]foundSum=newboolean[1];// Traverse the tree and check for the target sumsubtreeSum(root,foundSum,sum);// Return true if a subtree with the given sum was foundreturnfoundSum[0];}publicstaticvoidmain(String[]args){// Creating the given binary tree// 1// / \// 3 6// / \ /// 5 9 8Noderoot=newNode(1);root.left=newNode(3);root.right=newNode(6);root.left.left=newNode(5);root.left.right=newNode(9);root.right.left=newNode(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 treeclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Function to calculate the sum of the subtree # rooted at the given nodedefsubtreeSum(root,foundSum,target):# Base case: If the node is NULL, return 0ifrootisNone:return0# Calculate the sum of the current subtreecurrentSum=(root.data+subtreeSum(root.left,foundSum,target)+subtreeSum(root.right,foundSum,target))# If the current subtree sum matches the target,# set foundSum to TrueifcurrentSum==target:foundSum[0]=True# Return the current subtree sumreturncurrentSum# Function to check if there is a subtree with the given sumdefhasSubtreeWithGivenSum(root,sum):foundSum=[False]# Traverse the tree and check for the target sumsubtreeSum(root,foundSum,sum)# Return true if a subtree with the given sum was foundreturnfoundSum[0]if__name__=="__main__":# Creating the given binary tree# 1# / \# 3 6# / \ /# 5 9 8root=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 sumusingSystem;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGfG{// Function to calculate the sum of the subtree // rooted at the given nodestaticintSubtreeSum(Noderoot,refboolfoundSum,inttarget){// Base case: If the node is NULL, return 0if(root==null)return0;// Calculate the sum of the current subtreeintcurrentSum=root.data+SubtreeSum(root.left,reffoundSum,target)+SubtreeSum(root.right,reffoundSum,target);// If the current subtree sum matches the target, // set foundSum to trueif(currentSum==target){foundSum=true;}// Return the current subtree sumreturncurrentSum;}// Function to check if there is a subtree with the given sumstaticboolHasSubtreeWithGivenSum(Noderoot,intsum){boolfoundSum=false;// Traverse the tree and check for the target sumSubtreeSum(root,reffoundSum,sum);// Return true if a subtree with the given sum was foundreturnfoundSum;}staticvoidMain(string[]args){// Creating the given binary tree// 1// / \// 3 6// / \ /// 5 9 8Noderoot=newNode(1);root.left=newNode(3);root.right=newNode(6);root.left.left=newNode(5);root.left.right=newNode(9);root.right.left=newNode(8);Console.WriteLine(HasSubtreeWithGivenSum(root,17));}}
JavaScript
// JavaScript program to find if there is a subtree with// given sum// Node definition for a binary treeclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Function to calculate the sum of the subtree // rooted at the given nodefunctionsubtreeSum(root,foundSum,target){// Base case: If the node is NULL, return 0if(root===null)return0;// Calculate the sum of the current subtreeletcurrentSum=root.data+subtreeSum(root.left,foundSum,target)+subtreeSum(root.right,foundSum,target);// If the current subtree sum matches the target, // set foundSum to trueif(currentSum===target){foundSum.value=true;}// Return the current subtree sumreturncurrentSum;}// Function to check if there is a subtree with the given sumfunctionhasSubtreeWithGivenSum(root,sum){letfoundSum={value:false};// Traverse the tree and check for the target sumsubtreeSum(root,foundSum,sum);// Return true if a subtree with the given sum was foundreturnfoundSum.value;}// Creating the given binary tree// 1// / \// 3 6// / \ /// 5 9 8letroot=newNode(1);root.left=newNode(3);root.right=newNode(6);root.left.left=newNode(5);root.left.right=newNode(9);root.right.left=newNode(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.