I have tried bruteforce method but it's complexity is of O(n^2) , i am interested in O(n) or O(nlon n)

for the tree given above common ancestor of node 1 and 7 is 4. I am much interested in function not the whole program,function shoud take three argument as root of the tree, node1 and node 2