# Root to leaf Path Sum

Given a Binary Tree *T* and a sum *S*, write a program to **check whether there is a root to leaf path in that tree with the input sum S**.

**Example:**

Fig: Binary Tree

In the above example, the root is 8 & the leaf nodes are **9,1,2,3**. There are many **root to leaf paths** like:

**8->5->9**

**8->5->7->1**

**8->5->7->12->2**

And so on.

The sum for a root to leaf path is the sum of all intermediate nodes, the root & leaf node, i.e., sum of all the nodes on the path. Like for the first path in the above example the **root to leaf path sum is 22 (8+5+9)**

Our program must be to determine whether the given sum is same as anythe root to leaf path sum. There may be case that more than one root to leaf path has exactly same sum of S, but that’s not of any concern, Our function is a Boolean function to return only yes or not on basis of input.

Let for an example input:

**S= 26** & **T** be the above binary tree in example

Our program should return **"YES"** as there is a root to leaf path exists which is **8->4->11->3**

**S=8** & **T** be the above binary tree in example

Our program should return **"NO"** as there is no root to leaf path exists which has sum **8**

AlgorithmWe need to construct a Boolean function

hasRootToLeafSum ()which will accept a sum valueS& a binary treeTWe can implement the above function using recursion. The idea is to subtract current node value & continue to check for both subtrees recursively until we reach the base case. The base case can be of two type:

TRUEhere.TRUEhere.FunctionhasRootToLeafSum (sum value S, root of Binary tree T)## C++ implementation of Root to leaf Path Sum

need an explanation for this answer? contact us directly to get an explanation for this answerOutput