二叉树的创建及遍历_递归遍历_非递归遍历

缺少非递归后续遍历

 

#include <iostream>
#include <cstdio>
#include <malloc.h>
#include <stack>

using namespace std;

typedef struct tree{
    char a;
    tree *lchild;
    tree *rchild;
};

tree* create(tree *T){

    char c=getchar();
    if(c=='#'){
        T=NULL;
    }else{

        T=(tree*)malloc(sizeof(tree));
        T->a=c;
        if(!T){
            printf("\Error!n");
        }
        T->lchild=create(T->lchild);
        T->rchild=create(T->rchild);
    }
    return T;

}

void preorder(tree *T){
    if(T){
        printf("%c",T->a);
        preorder(T->lchild);
        preorder(T->rchild);
    }
}

void inorder(tree *T){
    if(T){
        inorder(T->lchild);
        printf("%c",T->a);
        inorder(T->rchild);
    }
}

void postorder(tree *T){
    if(T){
        postorder(T->lchild);
        postorder(T->rchild);
        printf("%c",T->a);
    }
}

//非递归先序遍历
void preorder1(tree *T){
    tree *p=T;
    stack<tree *> s;
    while(p!=NULL||!s.empty()){
        while(p!=NULL){
            printf("%c",p->a);
            s.push(p);
            p=p->lchild;
        }
        if(!s.empty()){
            p=s.top();
            s.pop();
            p=p->rchild;
        }
    }
}


//非递归中序遍历
void inorder1(tree *T){
    tree *p=T;
    stack<tree *> s;
    while(p!=NULL||!s.empty()){
        while(p!=NULL){
            s.push(p);
            p=p->lchild;
        }
        if(!s.empty()){
            p=s.top();
            printf("%c",p->a);
            s.pop();
            p=p->rchild;
        }
    }
}

//非递归后序遍历



int main()
{
    tree *T;
    printf("Plese input the tree's sequence:\n");
    T=create(T);
    printf("preorder:    ");
    preorder(T);
    printf("\n");

    printf("inorder:     ");
    inorder(T);
    printf("\n");

    printf("postorder:   ");
    postorder(T);
    printf("\n");


    printf("preorder(no_recersive):    ");
    preorder1(T);
    printf("\n\n");

    printf("inorder(no_recersive):     ");
    inorder1(T);
    printf("\n\n");

    return 0;
}

 

转载于:https://www.cnblogs.com/TWS-YIFEI/p/5794806.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值