Friday, February 20, 2015

Check if Two Nodes belongs to Same Parent or not

#include <stdio.h>
#include <stdlib.h>
 #include<stdbool.h>
struct Node
{
    int data;
    struct Node *left, *right;
};

// A utility function to create a new Binary Tree Node
struct Node *newNode(int item)
{
    struct Node *temp =  (struct Node *)malloc(sizeof(struct Node));
    temp->data = item;
    temp->left = temp->right = NULL;
    return temp;
}
bool isFUN(struct Node*root,struct Node *a,struct Node *b)
{
    if(root==NULL)
    {
        return 0;
    }
    if(((root->left==a)&&(root->right==b))||((root->left==b)&&(root->right==a)))
    {
        return true;
    }
    else
    {
        return isFUN(root->left,a,b)+isFUN(root->right,a,b);
    }
}

   

int main()
{
    struct Node *root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(3);
    root->left->left = newNode(4);
    root->left->right = newNode(5);
    root->left->right->right = newNode(15);
    root->right->left = newNode(6);
    root->right->right = newNode(7);
    root->right->left->right = newNode(8);

    struct Node *Node1,*Node2;
    Node1 = root->left->left;
    Node2 = root->left->right;
    isFUN(root,Node1,Node2)? puts("YES"): puts("NO");
    return 0;
}