Print Nodes having K leaves

PROBLEM :
Given a binary tree and a integer value K, the task is to find all nodes in given binary tree having K leaves in sub-tree rooted with them. If no node is found then print -1.


Input:
The first line of input  contains an integer T denoting the no of test cases. First line of each test case consists of two integers N and K, denoting Number of Nodes in binary Tree and number of leaves in sub-tree rooted with them. Second line of each test case consists of the struct Node, which has a data part which stores the data, pointer to left child and pointer to right child.


Output:
For each test case print the respective output in each line.


Constraints:
1<=T<=100
1<=N,K<=100
1<=value of nodes<=100


Example(To be used only for expected output):
Input:
2
2 1
0 1 L 0 2 R
4 2
0 1 L 0 2 R 2 3 R 2 4 L

Output:
-1
2

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

/*The Node is defined as follows:
struct Node
{
    int data ;
    struct Node * left, * right ;
};*/


/*You are required to complete below method */

int PrintNodes(Node *,int ,bool *) ;

int btWithKleaves(Node *ptr, int k)
{
    bool flag=false ;
    int temp=PrintNodes(ptr,k,&flag) ;
   
    if(!flag)
        cout<<-1 ;
    cout<<endl ;
}

int PrintNodes(Node *ptr,int k,bool *flag)
{
    if(ptr==NULL)
        return 0 ;
   
    if(ptr->left==NULL&&ptr->right==NULL)
        return 1 ;
       
    int curr = PrintNodes(ptr->left,k,&(*flag)) + PrintNodes(ptr->right,k,&(*flag)) ;
   
    if(curr==k)
    {
        cout<<ptr->data<<" " ;
        (*flag)=true ;
    }
   
    return curr ;
}

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )