简体   繁体   English

遍历二叉树迭代或递归-复杂度分析

[英]Traversing binary tree iterative or recursive - complexity analysis

I've heard some opinions that iterative lookup in Binary search tree is more efficient than the recursive way, is it true? 我已经听到一些意见,认为二叉搜索树中的迭代查找比递归方法更有效,这是真的吗?
(I know that in space terms the recusion is more expensive) (我知道从太空角度来看,修复费用更高)

In terms of time complexity (Big O), there should not be any difference if your algorithms are implemented properly. 就时间复杂度(Big O)而言,如果算法正确实现,应该没有任何区别。 Recursion is usually heavier with respect to space as each recursive call allocates new space on the stack. 由于每个递归调用都会在堆栈上分配新的空间,因此递归通常相对于空间而言更为沉重。 I am speaking about your particular binary search tree structure, but this is usually also true in general. 我说的是您的特定二进制搜索树结构,但是通常情况下也是如此。

递归搜索和迭代搜索之间确实没有区别,因为无论如何,遍历树的高度检查枯萎的左节点或右节点,但绝不会两者都使用(并且这对于迭代和递归都适用),因此您始终遍历树的高度。

Theoretically there is no change. 理论上没有改变。 The bigO will be O(n) for unbalanced and O(logn) for balanced BST. 对于不平衡,bigO将为O(n),对于平衡BST,bigO将为O(logn)。 Recursive traversal looks clean on paper. 递归遍历在纸上看起来很干净。 But it has lot of overhead. 但是它有很多开销。 When a function is called recursively the state of the calling function has to be stored in the stack and the control is passed to the called function. 递归调用函数时,必须将调用函数的状态存储在堆栈中,并将控件传递给被调用函数。 But when you do it iteratively, you do not have such overhead. 但是,当您反复进行操作时,就没有这样的开销。 So for practical purposes you should use iterative approach. 因此,出于实际目的,您应该使用迭代方法。

If you write a recursive code and if it turns out to be tail recursion, most modern compilers will try to optimize it by converting it to an iterative code. 如果您编写了一个递归代码,并且证明它是尾递归,则大多数现代编译器都会尝试通过将其转换为迭代代码来对其进行优化。

Much depends on your language implementation! 在很大程度上取决于您的语言实现! If procedure calls are expensive in your language, then hand-written iteration may be faster. 如果过程调用在您的语言中很昂贵,那么手写迭代可能会更快。 If procedure calls always push the stack, then hand-written iteration may save memory. 如果过程调用始终推栈,则手写迭代可能会节省内存。 In a functional language like Scheme, Haskell, ML, etc. (and I think also in a stack-based language like Postscript or FORTH), you can generally expect "tail recursion" as found in a tree lookup operation to be converted to iteration under the hood, so there is no difference. 在诸如Scheme,Haskell,ML等功能语言中(我也认为在诸如Postscript或FORTH之类的基于堆栈的语言中),通常可以期望在树查找操作中发现的“尾递归”将转换为迭代在引擎盖下,所以没有区别。 In fact, this particular form of tail recursion (where a function returns the value of a call to itself ) is likely be optimized by a compiler that does not even support full tail-call optimization (TCO). 实际上,这种特殊形式的尾部递归(函数将对自身的调用的值返回)可以甚至由甚至不支持完整尾部调用优化(TCO)的编译器进行优化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM