zoukankan      html  css  js  c++  java
  • 二叉搜索树的先序中序后序非递归遍历代码

    #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;
    }

  • 相关阅读:
    个人工作总结2
    个人工作总结1
    各种颜色代码
    第七周学习进度
    安卓的SlidingMenu配置
    第六周学习进度
    ecshop 首页调用指定分类下的销售排行
    EcShop首页显示特定分类的精品新品热销特价等推荐商品
    ecshop调用指定分类热销-新品-精品
    ecshop transport.js 和 jquery 冲突解决办法
  • 原文地址:https://www.cnblogs.com/wuxiangli/p/5630129.html
Copyright © 2011-2022 走看看