二叉搜索树的先序中序后序非递归遍历代码

#include<iostream>
#include<stack>
#include<vector>
using namespace std;
struct node
{
  int val;
  node *left,*right;
  node(int _val):val(_val),left(NULL),right(NULL){
   
  } 
};
struct bignode
{

  bool isfirst;
  node* pnode; 
};
void postorder(node* root)
{
 
 stack<bignode*> sta;
 node *p=root;
 while(p!=NULL||!sta.empty())
 {
  while(p)
  {
   bignode *tmp=new bignode();
   tmp->isfirst=true;
   tmp->pnode=p;
   sta.push(tmp);
   p=p->left;
  }
  if(!sta.empty())
  {
   bignode *tmp=sta.top();
   sta.pop();
   if(tmp->isfirst)
   {
    tmp->isfirst=false;
    sta.push(tmp);
    p=tmp->pnode->right;
   }
   else
   {
    cout<<tmp->pnode->val<<" ";
    p=NULL;
   }
  }
 }
}
void preorder(node* root)
{
    stack<node*> sta;
    node* p=root;
    while(p!=NULL||!sta.empty())
    {
     while(p){
  cout<<p->val<<" ";
      sta.push(p);
      p=p->left;
     }
     if(!sta.empty())
     {
      node * tmp=sta.top();
     
      sta.pop();
      p=tmp->right;
     }
     
    }
}
void inorder(node* root)
{
    stack<node*> sta;
    node* p=root;
    while(p!=NULL||!sta.empty())
    {
     while(p){
 
      sta.push(p);
      p=p->left;
     }
     if(!sta.empty())
     {
      node * tmp=sta.top();
      cout<<tmp->val<<" ";
      sta.pop();
      p=tmp->right;
     }
     
    }
}
int main()
{

   node n1(1),n2(2),n3(3),n4(4),n5(5),n6(6);
   n1.left=&n2;
   n1.right=&n3;
   n2.left=&n4;
   n2.right=&n5;
   n3.left=&n6;
   inorder(&n1);
 return 1;
}

原文地址:https://www.cnblogs.com/wuxiangli/p/5630129.html