Recursion or Iteration?

前端 未结 30 2177
小鲜肉
小鲜肉 2020-11-22 14:44

Is there a performance hit if we use a loop instead of recursion or vice versa in algorithms where both can serve the same purpose? Eg: Check if the given string is a palind

30条回答
  •  情话喂你
    2020-11-22 15:17

    If you're just iterating over a list, then sure, iterate away.

    A couple of other answers have mentioned (depth-first) tree traversal. It really is such a great example, because it's a very common thing to do to a very common data structure. Recursion is extremely intuitive for this problem.

    Check out the "find" methods here: http://penguin.ewu.edu/cscd300/Topic/BSTintro/index.html

提交回复
热议问题