K-Sum Paths
PROBLEM :
A binary tree and a number k are given. Print the count of every path in the tree with sum of the nodes in the path as k.
Input:
First line consists of T test cases. First line of every test case consists of N, denoting the number of Node is Binary tree. Second line consists of N spaced 3 elements denoting the Parent node, Child Node and a character denoting left or right child. Third line of every test case consists of a integer K.
Output:
Return the Count of number of paths in tree.
Constraints:
1<=T<=20
1<=N<=100
Example:
Input:
1
4
1 3 L 3 2 L 3 -1 R -1 1 R
4
Output:
2
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
/*Complete the function below
Node is as follows:
struct Node{
int data;
Node *left,*right;
Node(int d){
data=d;
left=right=NULL;
}
};*/
int CountKSum(Node *,int ,int ) ;
int printCount(Node *root,int k)
{
if(root==NULL)
return 0 ;
return CountKSum(root,0,k) + printCount(root->left,k) + printCount(root->right,k) ;
}
int CountKSum(Node *root,int curr,int k)
{
if(root==NULL)
return 0 ;
curr=curr+root->data ;
if(curr==k)
return 1 ;
else
return (CountKSum(root->left,curr,k) + CountKSum(root->right,curr,k)) ;
}
--------------------------------------------------------------------------------
A binary tree and a number k are given. Print the count of every path in the tree with sum of the nodes in the path as k.
Input:
First line consists of T test cases. First line of every test case consists of N, denoting the number of Node is Binary tree. Second line consists of N spaced 3 elements denoting the Parent node, Child Node and a character denoting left or right child. Third line of every test case consists of a integer K.
Output:
Return the Count of number of paths in tree.
Constraints:
1<=T<=20
1<=N<=100
Example:
Input:
1
4
1 3 L 3 2 L 3 -1 R -1 1 R
4
Output:
2
--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------
/*Complete the function below
Node is as follows:
struct Node{
int data;
Node *left,*right;
Node(int d){
data=d;
left=right=NULL;
}
};*/
int CountKSum(Node *,int ,int ) ;
int printCount(Node *root,int k)
{
if(root==NULL)
return 0 ;
return CountKSum(root,0,k) + printCount(root->left,k) + printCount(root->right,k) ;
}
int CountKSum(Node *root,int curr,int k)
{
if(root==NULL)
return 0 ;
curr=curr+root->data ;
if(curr==k)
return 1 ;
else
return (CountKSum(root->left,curr,k) + CountKSum(root->right,curr,k)) ;
}
--------------------------------------------------------------------------------
Comments
Post a Comment