我应该尽可能避免递归吗

我应该尽可能避免递归吗

本文介绍了我应该尽可能避免递归吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这种情况下,我不能同时使用它们而不会出现问题,因为我已经确信循环更容易理解,并且我会尝试始终使用它们.但是后来我偶然发现了这一点(二进制搜索树的C ++函数):

This is not a case where I can use both without problems, because I'm already convinced that loops are much easier to understand and I try to always use them. But then I stumble upon this (C++ function for binary search tree):

Node* Insert(Node* &rootptr,Node* data) {
    if (rootptr == nullptr) {
        rootptr = data;
    }
    else if (data->number <= rootptr->number) {
        rootptr->leftptr = Insert(rootptr->leftptr,data);
    }
    else {
        rootptr->rightptr = Insert(rootptr->rightptr,data);
    }
        return rootptr;
}

当我尝试思考如何通过循环实现时,我的想法被震撼了.好吧,那为什么要受苦呢?在这种情况下,请使用递归.但是我的头脑被震撼的事实实际上表明了递归的危害性,因为当您查看它时,您并不了解它的确切作用.是的,它很整洁,但是当它同时执行多项操作并且您并没有真正理解正在发生的事情时,这是一种危险的整洁.

And my mind gets blown when I try to think how to make it through loops. Well, why to suffer then? Use recursion if it's the case. But the fact that my mind gets blown actually shows how harmful recursion is, because when you look at it you don't understand what it exactly does. Yes, it's neat, but it's a dangerous kind of neat, when it does several things at the same time and you don't really comprehend what is happening.

所以在我看来,有3种情况:当递归很简单并且没有理由要解决时,当递归很复杂并且您使您的代码不可读时,当然有些情况下没有其他方法,所以您只是必须使用它,例如 Ackermann函数.为什么要使用它(除了某些特定情况)?

So in my opinion there are 3 cases: when recursion is simple and there's no reason to cope with it, when recursion is complex and you make your code unreadable, and of course some cases when there's no other way, so you just have to use it, like with Ackermann function. Why to use it then (besides some specific cases)?

推荐答案

递归可以更加清晰.递归的唯一担心是,如果使用过多堆栈,则可以粉碎堆栈.例如,Linux通常具有2MB的堆栈,因此您不想递归数百万行.递归只有O(log n)深的二叉树可能很好.

Recursion can be a lot more clear. The only worry with recursion is that you can smash the stack if you use it too much. For example linux typically has a 2MB stack so you don't want to recurse millions of lines deep. Recursing a binary tree that is only O(log n) deep is probably fine.

在这种情况下,用如下所示的循环替换它非常简单,但并非总是如此.

In this case it is fairly simple to replace it with a loop like the following, but it is not always the case.

 Node* Insert(Node* &rootptr,Node* data) {
        Node** p=&rootptr;
        while ((*p) != nullptr) {
            if (data->number <= (*p)->number) {
                p=&(*p)->leftptr;
            }
            else {
                p=&(*p)->rightptr;
            }
        }
        (*p) = data;
        return data;
}

这篇关于我应该尽可能避免递归吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 06:11