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

问题描述

我很困惑.迭代也是递归吗?

在递归中,所有内容都在堆栈中处理,迭代(循环)是否也在堆栈中处理?

In recursion, everything is processed in stack, does iteration(loops) are also processed in stack?

如果我们深入研究它们的处理,则递归的时间和空间复杂度会根据条件而增加,而迭代时间的复杂度会随着空间复杂度的增加而保持不变.

if we go deep into their processing, recursion's time and space complexity increases according to the condition, whereas iteration time complexity increases by space complexity remains constant.

有人可以在这个话题上更深入地阐明我吗.

can anyone clarify me more deeply on this topic.

推荐答案

不,它们是不同的概念.

No, they're different concepts.

  • 迭代问题时,您需要一步一步地(迭代地)解决问题.
  • 使用递归时,您通过递归调用(再次调用自身代码")逐层解决问题.

有可能(而且很可能)将两个概念结合在实际代码中.

It's possible (and very likely) to combine both concepts in real code.

例如,要遍历某些树结构(JSON或XML),通常会得到一些类似的功能(伪代码):

For example, to walk through some tree structure (JSON or XML), you'd typically end up with some function like this (pseudo code):

function parseNode(node) {
    // process this node
    switch (node.type) {
        // ...
    }

    foreach (child in node.children) // iterate over all child nodes
        parseNode(child) // this is the recursive call
}

让我们假设您有以下带有节点的树:

Let's assume you've got the following tree with nodes:

  A
  |
B-+-C
|   |
E F-+-G

要开始解析树,请调用parseNode(A).

To start parsing the tree, you'd call parseNode(A).

这将按以下顺序触发处理:A,B,E,C,F,G

This would trigger the processing in the following order: A, B, E, C, F, G

如您所见,这将逐个树枝地行走.当向下移动一个步骤/深度时,您将获得一个递归调用.每当您切换到下一个兄弟姐妹时,您就在进行迭代.

As you can see, this will walk the tree branch by branch. When going down by one step/depth, you've got a recursive call. Whenever you switch to the next sibling, you're iterating.

这篇关于迭代是递归吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 20:36