Kymane Llewellyn
Kymane Llewellyn

Reputation: 51

When printing out all nodes in a tree, is recursion or iteration more efficient?

I'm kind of confused. I see many people saying recursion is less efficient but by using an iterative method, wouldn't I have to allocate my stack in the heap, which would then make my program slower?

Thoughts?

Upvotes: 0

Views: 46

Answers (1)

Papai from BEKOAIL
Papai from BEKOAIL

Reputation: 1529

I see many people saying recursion is less efficient

It's totally depends on you how you can handle base-case when the tree is big (having greater depths). People like me, not consider the fact that recursion is less efficient, rather I always found recursion will give you more power (less calculated risk) for traversing the tree in some fashion (IN, PRE, POST, LEVEL).

wouldn't I have to allocate my stack in the heap

NO.

Because, to print the tree iteratively you can design your own stack-like structure, using array or some similar fashioned concept.

Though some language stores every object (considering array is an object) in heap-memory (for example - Java).

Upvotes: 1

Related Questions