[转]非递归遍历二叉树

原文详见:http://coolshell.cn/articles/9886.html

#include 

 

 

 
  
 
  
class Node
{
public:

<span class="kwrd">int</span> <span class="kwrd">value</span>;   <span class="rem">/**< 节点值 */</span>
Node *left;  <span class="rem">/**< 节点左子树 */</span>
Node *right; <span class="rem">/**< 节点右子树 */</span>

};

class Iterator
{
public:

<span class="kwrd">virtual</span> Node* next() = 0;

};

class InorderIterator : public Iterator
{
public:

InorderIterator(Node *node)
{
    Node *current = node;
    <span class="kwrd">while</span> (NULL != current)
    {
        m_stack.push(current);
        current = current->left;
    }
}

<span class="kwrd">virtual</span> Node* next()
{
    <span class="kwrd">if</span> (m_stack.empty())
    {
        <span class="kwrd">return</span> NULL;
    }
    Node *top = m_stack.top();
    m_stack.pop();
    <span class="kwrd">if</span> (NULL != top->right)
    {
        Node *current = top->right;
        <span class="kwrd">while</span> (NULL != current)
        {
            m_stack.push(current);
            current = current->left;
        }
    }
    <span class="kwrd">return</span> top;
}

private:

std::stack<Node*> m_stack;

};


你可能感兴趣的:([转]非递归遍历二叉树)