1

Has anyone written or thought about writing an iterator for a composite (tree) structure without using recursion? If so can you share your ideas? Thks

Edit: I was thinking of Java for lang.

2 Answers 2

1

Traversing a tree without recursion is simple enough. Assuming a binary tree, each node presumably has three references to other nodes. Left child, right child and parent. So assuming a depth-first left to right iteration order, you follow the left-child references in a while-lop (pseudocode while current.left-child != null, current = current.left-child) if there is no left-child, you try the right child. If there is no right child either, you go up until you find a right-child (while current.right-child == null, current = current.parent)

You haven't specified a language, but since you want to avoid recursion, I'm going to assume it's an imperative language of some sort, and then the above should be possible.

In short, your iterator must hold a reference to the current node, and some information about which way it's travelling.

Sign up to request clarification or add additional context in comments.

2 Comments

Agree with the binary tree traversal, but I didnt want to assume a binary tree.
Well, it's hard to traverse a tree without making some kind of assumption about its structure. The same approach can be trivially modified for any tree structure. Go through its children, then up to the parent and try the next child node
0

You might get some inspiration from this SO question: Post order traversal of binary tree without recursion All what you need is to extend the algorithm to non binary trees.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.