Chinaunix首页 | 论坛 | 博客
  • 博客访问: 38502
  • 博文数量: 64
  • 博客积分: 2640
  • 博客等级: 少校
  • 技术积分: 670
  • 用 户 组: 普通用户
  • 注册时间: 2010-01-26 13:15
文章分类
文章存档

2010年(64)

我的朋友
最近访客

分类: C/C++

2010-01-26 13:46:54

2008-10-02 11:33



#include<iostream>
using namespace std;

struct node{
       int data;
       node* leftchild;
       node* rightchild;
   };
 
class Stack{
      public:
      Stack();
      void Push(node* n);
      void Pop();
      node* GetTop();
      bool Is_empty();
      private:
      node* data[100];
      int top;
};

class BST{
      public:
      BST();
      void Insert(int i);
      void Order();
      private:
      node* root;
      void Insert(node* &n,int i);
};

int main(void){
    BST a;
    int n;
   
    cin>>n;
    while(n!=-1){
          a.Insert(n);
          cin>>n;
    }
   
    a.Order();
    system("pause");
   
    return 0;
}

Stack::Stack(){
       top = -1;
}

void Stack::Push(node* n){
     if(top==-1){
        data[0] = n;
        top = 0;
        return;
     }
     if(top+1>=100){
        cout<<"Stack full!";
        system("pause");
        exit(0);
     }
     top++;
     data[top] = n;
}

void Stack::Pop(){
     if(top==-1){
         cout<<"Stack empty!";
         system("pause");
         exit(0);
     }
     top--;
}

node* Stack::GetTop(){
      if(top==-1){
         cout<<"Stack empty!";
         system("pause");
         exit(0);
      }
      return data[top];
}
    
bool Stack::Is_empty(){ return top==-1; }
     
BST::BST(){
     root = 0;
}

void BST::Insert(node* &n,int i){
     if(!n){
        n = new node;
        n->data = i;
        n->leftchild = n->rightchild = 0;
        return;
     }
     if(n->data>=i) Insert(n->leftchild,i);
     else Insert(n->rightchild,i);
}

void BST::Insert(int i){
     Insert(root,i);
}

void BST::Order(){
     Stack st;
     node* p = root;
     do{
           while(p){
                 st.Push(p);
                 p = p->leftchild;
           }
           if(!st.Is_empty()){
              p = st.GetTop();
              st.Pop();
              cout<<p->data<<" ";
              p = p->rightchild;
          }
     }while(!st.Is_empty()||p);//若遍历完左子树和根时st.Is_empty()==true,

                               //而此时还没有遍历完,故要加上||p

}


阅读(208) | 评论(0) | 转发(0) |
0

上一篇:dijkstra算法

下一篇:Floyd算法

给主人留下些什么吧!~~