|
| 1 | +#include <iostream> |
| 2 | +using namespace std; |
| 3 | + |
| 4 | +// A Binary Tree Node |
| 5 | +struct Node |
| 6 | +{ |
| 7 | + struct Node *left, *right; |
| 8 | + int key; |
| 9 | +}; |
| 10 | + |
| 11 | +// Utility function to create a new tree Node |
| 12 | +Node* newNode(int key) |
| 13 | +{ |
| 14 | + Node *temp = new Node; |
| 15 | + temp->key = key; |
| 16 | + temp->left = temp->right = NULL; |
| 17 | + return temp; |
| 18 | +} |
| 19 | +Node* LCA(Node * root, int n1,int n2) |
| 20 | +{ |
| 21 | + // Your code here |
| 22 | + if (root == NULL) |
| 23 | + return root; |
| 24 | + if (root->key == n1 || root->key == n2) |
| 25 | + return root; |
| 26 | + |
| 27 | + Node* left = LCA(root->left, n1, n2); |
| 28 | + Node* right = LCA(root->right, n1, n2); |
| 29 | + |
| 30 | + if (left != NULL && right != NULL) |
| 31 | + return root; |
| 32 | + if (left != NULL) |
| 33 | + return LCA(root->left, n1, n2); |
| 34 | + |
| 35 | + return LCA(root->right, n1, n2); |
| 36 | +} |
| 37 | + |
| 38 | +// Returns level of key k if it is present in |
| 39 | +// tree, otherwise returns -1 |
| 40 | +void search(struct Node* root,int a,int level,int &get_level) |
| 41 | +{ |
| 42 | + if(root==NULL) |
| 43 | + { |
| 44 | + return; |
| 45 | + } |
| 46 | + if(root->key==a) |
| 47 | + { |
| 48 | + get_level = level; |
| 49 | + } |
| 50 | + search(root->left,a,level+1,get_level); |
| 51 | + search(root->right,a,level+1,get_level); |
| 52 | +} |
| 53 | + |
| 54 | +int findDistance(Node* root, int a, int b) |
| 55 | +{ |
| 56 | + // Your code here |
| 57 | + int level = 0; |
| 58 | + int x,y=0; |
| 59 | + Node* lca = LCA(root, a , b); |
| 60 | + search(lca,a,0,x); |
| 61 | + search(lca,b,0,y); |
| 62 | + return x + y; |
| 63 | +} |
| 64 | + |
| 65 | +// Driver program to test above functions |
| 66 | +int main() |
| 67 | +{ |
| 68 | + // Let us create binary tree given in |
| 69 | + // the above example |
| 70 | + Node * root = newNode(1); |
| 71 | + root->left = newNode(2); |
| 72 | + root->right = newNode(3); |
| 73 | + root->left->left = newNode(4); |
| 74 | + root->left->right = newNode(5); |
| 75 | + root->right->left = newNode(6); |
| 76 | + root->right->right = newNode(7); |
| 77 | + root->right->left->right = newNode(8); |
| 78 | + cout << "Dist(4, 5) = " << findDistance(root, 4, 5); |
| 79 | + cout << "\nDist(4, 6) = " << findDistance(root, 4, 6); |
| 80 | + cout << "\nDist(3, 4) = " << findDistance(root, 3, 4); |
| 81 | + cout << "\nDist(2, 4) = " << findDistance(root, 2, 4); |
| 82 | + cout << "\nDist(8, 5) = " << findDistance(root, 8, 5); |
| 83 | + return 0; |
| 84 | +} |
0 commit comments