-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathcode_1.cpp
More file actions
120 lines (107 loc) · 2.52 KB
/
code_1.cpp
File metadata and controls
120 lines (107 loc) · 2.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
//
// code_1.cpp
// Algorithm
//
// Created by Mohd Shoaib Rayeen on 15/04/19.
// Copyright © 2019 Shoaib Rayeen. All rights reserved.
//
#include <iostream>
#include <queue>
using namespace std;
struct bnode {
int data;
bnode *left;
bnode *right;
};
class btree {
public:
bnode *root;
btree();
void insert();
void display();
bnode* newNode(int);
bnode* findDistUtil(bnode*, int, int, int &,int &, int &, int);
int findLevel(bnode* , int, int);
int findDistance(bnode*,int, int);
};
btree::btree() {
root = NULL;
}
bnode* btree:: newNode(int value) {
bnode* temp=new bnode;
temp->data=value;
temp->left=NULL;
temp->right=NULL;
return temp;
}
void btree:: insert() {
root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
}
void btree::display() {
insert();
int n;
cout << "\nEnter 1st Node\t:\t";
cin >> n;
int k;
cout << "\nEnter 2nd Node\t:\t";
cin >> k;
cout << "\nDistance Between them\t:\t" << findDistance(root, n, k) << endl;
}
int btree::findLevel(bnode *root, int k, int level) {
if (root == NULL) {
return -1;
}
if (root->data == k) {
return level;
}
int l = findLevel(root->left, k, level+1);
return (l != -1)? l : findLevel(root->right, k, level+1);
}
bnode* btree::findDistUtil(bnode* root, int n1, int n2, int &d1, int &d2, int &dist, int lvl) {
if (root == NULL) {
return NULL;
}
if (root->data == n1) {
d1 = lvl;
return root;
}
if (root->data == n2) {
d2 = lvl;
return root;
}
bnode *left_lca = findDistUtil(root->left, n1, n2, d1, d2, dist, lvl+1);
bnode *right_lca = findDistUtil(root->right, n1, n2, d1, d2, dist, lvl+1);
if (left_lca && right_lca) {
dist = d1 + d2 - 2*lvl;
return root;
}
return (left_lca != NULL)? left_lca: right_lca;
}
int btree::findDistance(bnode *root, int n1, int n2) {
int d1 = -1, d2 = -1, dist;
bnode *lca = findDistUtil(root, n1, n2, d1, d2, dist, 1);
if (d1 != -1 && d2 != -1) {
return dist;
}
if (d1 != -1) {
dist = findLevel(lca, n2, 0);
return dist;
}
if (d2 != -1) {
dist = findLevel(lca, n1, 0);
return dist;
}
return -1;
}
int main() {
btree obj;
obj.display();
cout << "\n";
return 0;
}