二叉树 前序 中序 后序 非递归遍历方式

代码如下:

struct Node{
 Node(int _data):data(_data),left(NULL),right(NULL){}
 int data;
 Node* left;
 Node* right;
};
void initTree(Node** head){
  *head=new Node(1);
  (*head)->left=new Node(2);
  (*head)->right=new Node(3);
  (*head)->left->left=new Node(4);
  (*head)->left->right=new Node(5);
}
void desTree(Node* head){
  if(head->left) desTree(head->left);
  if(head->right) desTree(head->right);
  delete head;
}
void preNonRecursive(Node* head){
  stack<Node*> s;
  s.push(head);
  cout<<"pre order is :";
  while(!s.empty()){
    Node* n1=s.top();
    s.pop();
   cout<<n1->data<<" ";
   if(n1->right!=NULL) s.push(n1->right);
   if(n1->left!=NULL) s.push(n1->left);
  }
  cout<<endl;
}
void inNonRecursive(Node* head){
  stack<Node*> s;
  Node* cur=head;
  cout<<"in order is:";
  while(!s.empty()||cur!=NULL){
    if(cur!=NULL){
      s.push(cur);
      cur=cur->left;
    }else{
      cur=s.top();s.pop();
      cout<<cur->data<<" " ;
      cur=cur->right;
    }
  }
  cout<<endl;
}
void postNonRecursive(Node* head){
  stack<Node*> s,sVisit;
  s.push(head);
  while(!s.empty()){
   Node* p=s.top();s.pop();
   sVisit.push(p);
   if(p->left) s.push(p->left);
   if(p->right) s.push(p->right);
  }
  cout<<"post order is :";
  while(!sVisit.empty()){
    Node* p=sVisit.top();sVisit.pop();
    cout<<p->data<<" " ;
  }
  cout<<endl;
  


}
int main(){
 Node* head;
 initTree(&head);
 preNonRecursive(head);
 inNonRecursive(head);
 postNonRecursive(head);
 desTree(head);
 return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值