Skip to content

Instantly share code, notes, and snippets.

@ravichandrae
Last active January 23, 2017 12:46
Show Gist options
  • Save ravichandrae/b0210f8c14b9bfe0940a8f11f5507ae6 to your computer and use it in GitHub Desktop.
Save ravichandrae/b0210f8c14b9bfe0940a8f11f5507ae6 to your computer and use it in GitHub Desktop.
Path length between two nodes in a full binary tree
#include <iostream>
using namespace std;
int path_length(int p, int q) {
int len = 0;
//Until p and q reach their lowest common ancestor.
while (p != q ) {
if( p > q ) {
p = p/2;
len++;
}
else if( q > p ) {
q = q/2;
len++;
}
}
return len;
}
int main() {
int t;
cin >> t;
while(t--) {
int i,j;
cin >> i >> j;
cout << path_length(i, j) << endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment