中序遍历

来源:互联网 发布:通信网络定义 编辑:程序博客网 时间:2024/05/22 12:50
#include<cstdio> ///中序遍历#include<cstdlib>#include<stack>using namespace std;typedef struct Node{    int k;    Node  *lchild,*rchild;}Node,*Link;Link p;int x;void create(Link& T){    scanf("%d",&x);    if(x==-1) return ;    T=(Link)malloc(sizeof(Node));    T->lchild=T->rchild=NULL;    T->k=x;    create(T->lchild);    create(T->rchild);}void print(Link T)//递归 先序{    if(!T) return;    printf("%d ",T->k);    print(T->lchild);    print(T->rchild);}// top pop push empty sizevoid stack_print(Link T)//栈 非递归中序{    Link p;    stack<Link>s;    s.push(T);    while(!s.empty()){        while(p=s.top()) //向左走到尽头            s.push(p->lchild);        s.pop(); // 空指针退栈        if(!s.empty()){ //向右            p=s.top();            s.pop();            printf("%d ",p->k);            s.push(p->rchild);        }    }}void stack_print_2(Link T)//栈 非递归中序{    Link p;    stack<Link>s;    p=T;    while(p||!s.empty()){        if(p){                 //向左走到尽头            s.push(p);p=p->lchild;        }        else{ //向右            p=s.top();            s.pop();            printf("%d ",p->k);            p=p->rchild;        }    }}int main(){    Link T=NULL;    create(T);    puts("递归先序遍历");    print(T);    puts("");    puts("非递归中序遍历");    stack_print(T);    puts("");    return 0;}/// 1 5 9 10 11 -1 -1 1 6 -1 -1 -1 -1 8 -1 -1 7 7 -1 -1 2 -1 -1

0 0
原创粉丝点击