Algorithm for creating Iterator for BinaryTree class

☆樱花仙子☆ 提交于 2019-12-14 03:57:34

问题


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:

  1. To start the iteration you would find the left-most node.
  2. To go to the next node the operation depends on where you currently are:
    1. 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).
    2. 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.
  3. 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:

  1. Keep going down and to the left
  2. Every time you come across a right branch, add it to the stack
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!