当有2个递归语句如下面的程序时,如何执行递归? [英] How is recursion executed when there are 2 recursive statements like the program below?

查看:138
本文介绍了当有2个递归语句如下面的程序时,如何执行递归?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我之前发过一个问题但是我不够清楚。我很抱歉这个混乱,但我的意思是,如果有这样的程序:

I had posted a question earlier however I wasn't clear enough. I am sorry for the confusion but what I meant was if there is a program like :

TreeNode createMinBST(int arr[], int start, int end) {
    if(end< start) return null;

    int mid = (start+end)/2;
    Treenode n= new Treenode(arr[mid]);
    n.left= createMinBST(arr, start, mid-1)  //LINE a
    n.right= createMinBST(arr, mid+1, end);  //LINE b
    return n;
}

LINE a和LINE b如何展开(就像在编码面试书中所说的那样) )或它是如何工作的? LINE a是否一直到基本情况并返回值,然后LINE b执行?或者两个递归语句同时归结为基本情况?

How does LINE a and LINE b unroll(like it said in coding interview book) or how does it work? Does LINE a go all the way to the base case and return values and then LINE b executes? Or both the recursive statements go down to the base case simultaneously?

如果有人可以解释从上面给出的代码创建最小BST的等级明确路径,它将是真的有助于理解多个递归语句(此处为2-线a和线b)如何发生

If someone could explain level wise path for creating a Minimal BST from the code given above, it will be really helpful to understand how multiple recursive statements (here 2- Line a and Line b) takes place

非常感谢

推荐答案

查看您的代码,您正在构建树,就像进行深度优先搜索一样。所以你要更深入(在你的情况下留下了东西),直到没有更多的元素要处理,然后你回到一个级别,然后再次回落。

Looking at your code you're building your tree the same way you'd do a "depth-first search". So you're going deeper (depper left in your case) until there's no more element to process, then you're going back up one level and then again back down.

(顺便说一句,你的'A行'在结尾处缺少一个分号)

通常情况下,学习或尝试弄清楚递归调用是如何工作的,打印调用很方便。

As is often the case when learning or trying to figure out how recursive calls are working, it is convenient to print out the calls.

例如,在你的情况下你的起始数组包含来自[10..24]的数字然后你的电话可能如下所示:

For example in your case if your starting array contains numbers from [10..24] then your calls may look like this:

Calling minBST on 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24

    Calling minBST (left) on 10, 11, 12, 13, 14, 15, 16

        Calling minBST (left) on 10, 11, 12

            Calling minBST (left) on 10

            Calling minBST (right) on 12

        Calling minBST (right) on 14, 15, 16

            Calling minBST (left) on 14

            Calling minBST (right) on 16

    Calling minBST (right) on 18, 19, 20, 21, 22, 23, 24

        Calling minBST (left) on 18, 19, 20

            Calling minBST (left) on 18

            Calling minBST (right) on 20

        Calling minBST (right) on 22, 23, 24

            Calling minBST (left) on 22

            Calling minBST (right) on 24

这篇关于当有2个递归语句如下面的程序时,如何执行递归?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆