Last active
January 23, 2017 12:46
-
-
Save ravichandrae/b0210f8c14b9bfe0940a8f11f5507ae6 to your computer and use it in GitHub Desktop.
Path length between two nodes in a full binary tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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