如何绘制递归树

时间:2012-11-18 14:31:02

标签: java algorithm recursion

我试图了解如何绘制递归树,例如: 取自here

enter image description here

在右侧,您可以看到特定问题的递归树。

任何想法如何开始建立你的递归树,例如对于这个给定目标数量和一些权重(例如1,2,3)的函数,如果可以使用权重测量旧方法来计算目标

你需要为这个问题做出的基本观察是每个重量 矢量可以是: 1.从样品上放置天平的另一侧 2.将天平放在与样品相同的一侧 3.完全取消平衡

我不知道如何以编程方式进行铅笔和纸张更好地了解递归的工作原理。

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);

}

对于此问题并输入权重1,2,3和目标5,输出为:

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

你是如何开始构建树的?什么时候增加宽度和高度..?

1 个答案:

答案 0 :(得分:2)

每次递归调用时树的高度都会增加。在您的示例中,每次调用IsMeasurable3都会增加高度。

当从递归函数的相同调用进行多次调用时,树的宽度会增加。在您的示例中,IsMeasurable3被调用3次,因此树上最多有三个分支,直到递归级别。