void buildGraph(Node* root, unordered_map<int, vector<int>>& adj) {
if(root == NULL) {
return;
}
if(root->left) {
adj[root->data].push_back(root->left->data);
adj[root->left->data].push_back(root->data);
}
if(root->right) {
adj[root->data].push_back(root->right->data);
adj[root->right->data].push_back(root->data);
}
buildGraph(root->left, adj);
buildGraph(root->right, adj);
}
int findDist(Node* root, int a, int b) {
// Build Graph
unordered_map<int, vector<int>> adj;
buildGraph(root, adj);
// Perform BFS
queue<int> q;
unordered_set<int> st;
q.push(a);
st.insert(a);
int cnt = 0;
while(!q.empty()) {
int sz = q.size();
for(int i = 0; i < sz; i++) {
int curr = q.front();
q.pop();
if(curr == b) {
return cnt;
}
for(auto it : adj[curr]) {
if(st.find(it) == st.end()) {
q.push(it);
st.insert(it);
}
}
}
cnt++;
}
return -1;
}