Monday 3 September 2018

Find distance between two nodes in Binary tree & BST.

#include <bits/stdc++.h>

using namespace std;



struct Node {

    struct Node* left, *right;

    int key;

};



struct Node* newNode(int key)

{

    struct Node* ptr = new Node;

    ptr->key = key;

    ptr->left = ptr->right = NULL;

    return ptr;

}



// Standard BST insert function

struct Node* insert(struct Node* root, int key)

{

    if (!root)

        root = newNode(key);

    else if (root->key > key)

        root->left = insert(root->left, key);

    else if (root->key < key)

        root->right = insert(root->right, key);

    return root;

}



int result=0;

Node *temp=NULL;



int findvikas(Node *root,int a,int b) {

    if(root==NULL) return 0;

    if(root->key==a || root->key==b){

        temp = root;

        return 1;

    }

 

    int l = findvikas(root->left, a, b);

    int r = findvikas(root->right, a, b);

    // cout<<l<<" "<<r<<" "<<root->key<<endl;

    if(l!=0 && r!=0){

        result = l+r;

        return l+r;

    }



    if(result!=0) return max(l,r);

    if(l!=0) return l+1;

    if(r!=0) return r+1;

    return 0;

}

int cal(Node *root, int b) {

    if(root==NULL) return -1;

    if(root->key==b)

     return 0;

 

    int l = cal(root->left,b);

    int r = cal(root->right,b);

    // cout<<l<<" "<<r<<"  "<<root->key<<endl;

    if(l!=-1) return l+1;

    else if(r!=-1) return r+1;

    else return -1;

}

int main()

{

    struct Node* root = NULL;

    root = insert(root, 20);

    insert(root, 10);

    insert(root, 5);

    insert(root, 15);

    insert(root, 30);

    insert(root, 25);

    insert(root, 35);

    insert(root, 1);

    int a = 5, b = 25;

 

    int res = findvikas(root,a,b);

 

    if(result==0) {

        if(temp->key == a) a = b;

        cout<<"distance "<<cal(temp,a)<<endl;

    } else

    cout<<"distance "<<result;

 

    return 0;

}

No comments:

Post a Comment