#include <bits/stdc++.h>
using
namespace
std;
struct
Node {
int
data;
struct
Node* left;
struct
Node* right;
};
void
hasPathSum(
struct
Node* node,
int
sum,
int
& mini,
int
level)
{
if
(node == NULL)
return
;
int
subSum = sum - (node->data);
if
(node->left == NULL && node->right == NULL) {
if
(subSum == 0)
mini = min(level - 1, mini);
return
;
}
else
{
hasPathSum(node->left, subSum, mini, level + 1);
hasPathSum(node->right, subSum, mini, level + 1);
}
}
struct
Node* newnode(
int
data)
{
struct
Node* node =
new
Node;
node->data = data;
node->left = NULL;
node->right = NULL;
return
(node);
}
int
main()
{
int
sum = 16;
struct
Node* root = newnode(1);
root->left = newnode(10);
root->right = newnode(15);
root->left->left = newnode(5);
root->left->right = newnode(2);
int
mini = INT_MAX;
hasPathSum(root, sum, mini, 0);
if
(mini != INT_MAX)
printf
(
"There is a root-to-leaf path with sum %d\n"
"and the shortest path length is: %d"
,
sum, mini + 1);
else
printf
(
"There is no root-to-leaf path with sum %d"
, sum);
return
0;
}