I am trying to understand how to draw a recursion tree e.g.:
Taken from here

On the right you can see the recursion tree for the specific problem.
Any ideas how to you start build you recursion tree for example for this function which given a target amount and some weights (e.g. 1,2,3) it returns if its possible to compute the target using the old fashion measuring with weights.
The fundamental observation you need to make for this problem is that each weight in the
vector can be either:
1. Put on the opposite side of the balance from the sample
2. Put on the same side of the balance as the sample
3. Left off the balance entirely
I am not looking how to do it programmatically just pencil&paper to understand better how recursion works.
static Boolean IsMeasurable3(int left, int right, ArrayList<Integer> weights,int weightIndex) {
//Debug
//System.out.println("Left is " + left + " Right is " + right);
if (Math.abs(left - right) == 0){
System.out.println("Found it! Left is " + left + " Right is " + right);
return true;
}
if (weightIndex >= weights.size())
return false;
return IsMeasurable3(left + weights.get(weightIndex), right, weights,weightIndex + 1)
|| IsMeasurable3(left, right + weights.get(weightIndex), weights,weightIndex + 1)
|| IsMeasurable3(left, right, weights,weightIndex + 1);
}
For this problem and input weights 1,2,3 and target 5 the output is :
Left is 5 Right is 0
Left is 6 Right is 0
Left is 8 Right is 0
Left is 11 Right is 0
Left is 8 Right is 3
Left is 8 Right is 0
Left is 6 Right is 2
Left is 9 Right is 2
Left is 6 Right is 5
Left is 6 Right is 2
Left is 6 Right is 0
Left is 9 Right is 0
Left is 6 Right is 3
Left is 6 Right is 0
Left is 5 Right is 1
Left is 7 Right is 1
Left is 10 Right is 1
Left is 7 Right is 4
Left is 7 Right is 1
Left is 5 Right is 3
Left is 8 Right is 3
Left is 5 Right is 6
Left is 5 Right is 3
Left is 5 Right is 1
Left is 8 Right is 1
Left is 5 Right is 4
Left is 5 Right is 1
Left is 5 Right is 0
Left is 7 Right is 0
Left is 10 Right is 0
Left is 7 Right is 3
Left is 7 Right is 0
Left is 5 Right is 2
Left is 8 Right is 2
Left is 5 Right is 5
Found it! Left is 5 Right is 5
How do you start thinking to build the tree? When do you increase width and when height..?
The tree increases in height for each recursive call. In your example, each call to
IsMeasurable3increases the height.The tree increases in width when multiple calls are made from the same invocation of the recursive function. In your example,
IsMeasurable3is called 3 times, so there will be up to three branches on the tree down to recursive levels.