Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Monday, August 28, 2017

Nodes at given distance in binary tree From Target Node


Explanation :


Check if target Node is root then print all the nodes at distance k (Down Traversal).
Else
Create a function which tells you the distance of target node from root node and Check in left node of root that its distance is k or not , if so then print it else go to its right subtree , vice versa for other subtree..

Here k-d1-2 , 2 : root node,current node, dx=already traversed distance.

Code:


void printkdistanceNodeDown(node *root, int k)
{
    if(root==NULL || k<0)
    return;
    if(k==0)
    {
        cout<<root->data<<" ";
        return;
    }
    printkdistanceNodeDown(root->left,k-1);
    printkdistanceNodeDown(root->right,k-1);
}
int printkdistanceNode(node* root, node* target , int k)
{
if(root==NULL)
return -1;
if(root==target)
{
    printkdistanceNodeDown(root,k);
    return 0;
}
int d1=printkdistanceNode(root->left,target,k);
if(d1!=-1)
{
    if(d1+1==k)
    cout<<root->data<<" ";
    else
    {
        printkdistanceNodeDown(root->right,k-d1-2);
    }
    return 1+d1;
}
int d2=printkdistanceNode(root->right,target,k);
if(d2!=-1)
{

0 Comments:

Post a Comment

Stats