问题
I want to add Bi-Directional Iterator (like Iterator exported by std::set) in my Parametrized BinaryTree class but I'm unable to comeup with any algorithm.
Simply structure of Binary tree node is , it contains three pointers , left , right , parent:

回答1:
With the given structure you want to proceed like this:
- To start the iteration you would find the left-most node.
- To go to the next node the operation depends on where you currently are:
- If your node has a right child you go to this child and find its left-most successor (if there is no left child the node you are on is the next node).
- If you nodes doesn't have a right child you move up the chain of parents until you find a parent for which you used the link to the left node: the next node becomes this node.
- To move in the other direction you reverse the roles of left and right.
Effectively, this is implements a stack-less in-order traversal of the tree. If your tree isn't changed while iterating (an unlikely scenario) or you don't have a link to the parent node, you can maintain the stack explicitly in the iterator.
回答2:
A good approach to this issue may be to first write your recursive pre-order algorithm, without using templates, and then you can from that create a templated version and implement the correct Iterators.
Just a thought.
回答3:
You can't use recursion to implement an iterator in C++ because your iterator needs to return from all processing before it can return the result.
Only languages like C# and Python, that have a concept of yield
can use recursion to create iterators.
Your iterator needs to maintain a stack of yet-to-be-visited nodes.
Of the top of my head, I think the algorithm is something like:
- Keep going down and to the left
- Every time you come across a right branch, add it to the stack
- If at any point you can't go left, pop the first branch off the stack and begin visiting that in the same way.
来源:https://stackoverflow.com/questions/8961605/algorithm-for-creating-iterator-for-binarytree-class