二叉树非递归中序遍历(借用stack)

递归的中序遍历,

template  < class  Entry >
void  Binary_tree < Entry > ::recursive_inorder(Binary_node < Entry >   * sub_root,
                                           
void  ( * visit)(Entry ))
{
   
if (sub_root != NULL) {
      recursive_inorder(sub_root
->left, visit);
      (
*visit)(sub_root->data);
      recursive_inorder(sub_root
->right, visit);
   }

}

根据递归调用函数时栈的情况, 自己手动操作栈,
于是有

#include < stack >
using   namespace  std;

template 
< class  Entry >
void  Binary_tree < Entry > ::NonRecursiveInorder( void  ( * visit)(Entry))
{
    Binary_node
<Entry> *go=root;
    stack 
<Binary_node<Entry>* > stk;
    
while(!stk.empty() || go!=NULL)
    
{
        
if(go!=NULL)
        
{
            stk.push(go);
            go
=go->left;
        }

        
else
        
{
            go
=stk.top();
            stk.pop();
            (
*visit)(go->data);
            go
=go->right;
        }

    }
   
}
 


你可能感兴趣的:(tree,null,Class,Go)