Function to check there is path in the binary tree with a given sum

This function have trick call same function again for children nodes with remaining sum, at the end if sum become zero ie there is the path for a given sum.


static bool hasPathWithGivenSum(treeNode *rootNode, int sum) {

	// if we check complete tree and sum is zero  then return true
	if (rootNode == NULL)
		return (sum == 0);

	//remaining sum
	int remainingSum = sum - rootNode->val;

	// if root node have both child or both are null ie leaf Node
	if ((rootNode->leftChild && rootNode->rightChild)
			|| (!rootNode->leftChild && !rootNode->rightChild)) {

		return (hasPathWithGivenSum(rootNode->leftChild, remainingSum)
				|| hasPathWithGivenSum(rootNode->rightChild, remainingSum));

		//if right child is null
	} else if (rootNode->leftChild)
		return hasPathWithGivenSum(rootNode->leftChild, remainingSum);

	//if left child is null
	else
		return hasPathWithGivenSum(rootNode->rightChild, remainingSum);

}

above mention function is member function of my Tree ADT class you can check complete program here

A Developer
Gy@n!

About Gyaneshwar Pardhi

Exploring the world and trying to know how can i involve to make this perfect. Gy@n!
This entry was posted in c++, Data Structure, interview Question, Programming and tagged , . Bookmark the permalink.

Leave a comment