Learn-dsa..in 30 days!



























CC-7 : : Check Binary Tree path sum.

Description:

Given an integer as input, check if sum of node data of any path of Tree Nodes from root of Binary Tree to a particular node is same as input integer.

Test cases and expected outputs:

Input Parameters Expected outputs
Check path with sum: 48
Check path with sum: 49
Check path with sum: 87
48 Path sum Found? true
49 Path sum Found? false
87 Path sum Found? true

Pseudocode:

Method checkPathSum (root, SumToBeFound)

If node data of root is equal to sumToBeFound, and the root node has no children, return true.
Recursively call method checkPathSum() with left child of root as first argument and (sumTobeFound minus root.getNodeData()). If the recursively called method returns true, then return true from current method call also.
Recursively call method checkPathSum() with right child of root as first argument and (sumTobeFound minus root.getNodeData()). If the recursively called method returns true, then return true from current method call also.
If both above recursive calls return false, then return false from current method call also.


Code:

public boolean checkPathSum(BinTreeNode root, int sumToBeFound) throws Exception{
	if (root==null) {return false;}
	if ((root.getNodeData()==sumToBeFound) 
			&& (root.getLeftChild()==null) 
			&& (root.getRightChild()==null)) {
		return true;		
	}
	return checkPathSum(root.getLeftChild(),sumToBeFound-root.getNodeData())
			|| checkPathSum(root.getRightChild(),sumToBeFound-root.getNodeData());
}

Click here to download and run code and test cases !