栈 树
来源:互联网 发布:java 字符串包含汉字 编辑:程序博客网 时间:2024/05/21 04:02
-
-
- #include "stdafx.h"
- #include <iostream>
- using namespace std;
- typedef char ElemType;
-
-
- typedef struct Lnode
- {
- struct Bitnode* Tree;
- struct Lnode*next;
- }Lnode,*linkstack;
- typedef struct Bitnode
- {
- ElemType data;
- struct Bitnode *lchild,*rchild;
- }Bitnode,*BitTree;
-
-
-
-
- int initstack(linkstack &s)
- {
- s=new Lnode;
- s->next=NULL;
- return 1;
- }
- int Empty_stack(linkstack s)
- {if (s->next==NULL)return 1;
- else return 0;
- }
- int push(linkstack s,BitTree T)
- {linkstack p;
- p=new Lnode;
- if(!p){cout<<"分配内存失败"<<endl;return 0;}
- p->Tree=T;
- p->next=s->next;
- s->next=p;
- return 1;
- }
- int pop(linkstack s,BitTree &p)
- {linkstack temp;
- if(Empty_stack(s)){cout<<"栈空了"<<endl;return 0;}
- temp=s->next;
- p=temp->Tree;
- s->next=temp->next;
- free(temp);
- return 1;
- }
- int get_top(linkstack s,BitTree &p)
- {if(s->next==NULL){return 0;}
- else {p=s->next->Tree;return 1;}
- }
- void l_display(linkstack s)
- {while(s->next!=NULL)
- {s=s->next;
- if(s->Tree!=NULL)
- cout<<s->Tree->data;
- }
- }
-
-
- int CreatB_Tree(BitTree &T)
- {
- ElemType ch;
- ch=getchar();
- if(ch==' ')T=NULL;
- else
- {if(!(T=new Bitnode))cout<<"Error!"<<endl;
- T->data=ch;
- CreatB_Tree(T->lchild);
- CreatB_Tree(T->rchild);
- }
- return 1;
- }
-
-
- int Pr_Order_B_Tree(BitTree T)
- { BitTree p;
- linkstack s;
- initstack(s);
- push(s,T);
- while(!Empty_stack(s))
- {pop(s,p);
- while(p!=NULL)
- {cout<<p->data<<" ";
- if(p->lchild)push(s,p->rchild);
- p=p->lchild;
- }
- }
- cout<<endl;
- return 1;
- }
-
- int In_Order_B_Tree(BitTree T)
- {
- BitTree p;
- linkstack s;
- initstack(s);
-
- p=T;
- while(p||!Empty_stack(s))
- {while(p)
- {push(s,p);
- p=p->lchild;
- }
- pop(s,p);
- cout<<p->data<<" ";
- p=p->rchild;
-
-
- }
- cout<<endl;
- return 1;
- }
- int Po_Order_B_Tree(BitTree T)
- {
- BitTree p,q;
- linkstack s;
- initstack(s);
-
- p=T;q=NULL;
- while(p||!Empty_stack(s))
- {if(p!=q)
- {while(p!=NULL)
- {push(s,p);
- if(p->lchild)p=p->lchild;
- else p=p->rchild;
- }
- }
- if(Empty_stack(s))break;
- get_top(s,q);
- if(q->rchild==p)
- {pop(s,p);
- cout<<p->data<<" ";
-
- }
- else p=q->rchild;
- }
- cout<<endl;
- return 1;
- }
- int InOrder_B_Tree(BitTree T)
- {
- BitTree p;
- linkstack s;
- initstack(s);
-
- push(s,T);
-
- while(!Empty_stack(s))
- { while(get_top(s,p)&&p)push(s,p->lchild);
- pop(s,p);
-
-
- if(!Empty_stack(s))
- {pop(s,p);
- if(p!=NULL)cout<<p->data<<" ";
- push(s,p->rchild);
- }
- }cout<<endl;
- return 1;
- }
- int main()
- {
-
-
- BitTree T;
- CreatB_Tree(T);
-
-
- Pr_Order_B_Tree(T);
- In_Order_B_Tree(T);
- InOrder_B_Tree(T);
- Po_Order_B_Tree(T);
-
-
-
- int m;
- cin>>m;
- return 1;
- }
-