简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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