The algorithm that you described is unacceptable because there can be no more than 100 lines, so if the number of nodes in the tree doubles in each line, you will end up with 2 ^ 101 nodes in your tree in the worst case.
This problem can be solved by simple dynamic programming, where at each step you need to choose a minimum between the first and second spaces:
T(0, j) = 1 T(i, j) = 1+min( abs(pos(i, j)-pos(i-1, 0)) + T(i-1, 0), abs(pos(i, j)-pos(i-1, 1)) + T(i-1, 1))
Where i is the string i th, and j is either 0 or 1 , indicating which space we chose in the last turn. Here is a Java implementation example:
import static java.lang.Math.abs; import static java.lang.Math.min; public class Main { public static int solve(int[][] P) { int a = 1, b = 1; for (int i = 1; i < P.length; i++) { int na = 1 + min( abs(P[i][0] - P[i - 1][0]) + a, abs(P[i][0] - P[i - 1][1]) + b); int nb = 1 + min( abs(P[i][1] - P[i - 1][0]) + a, abs(P[i][1] - P[i - 1][1]) + b); a = na; b = nb; } return min(a, b); } public static void main(String... args) { System.out.println(solve(new int[][]{ {3, 6}, {2, 8}, {4, 5}, {7, 8}, {3, 10}, })); System.out.println(solve(new int[][]{ {4, 7}, {2, 9}, {8, 11} })); } }