zoukankan      html  css  js  c++  java
  • 二叉树的创建及遍历_递归遍历_非递归遍历

    缺少非递归后续遍历

    #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:
    ");
        T=create(T);
        printf("preorder:    ");
        preorder(T);
        printf("
    ");
    
        printf("inorder:     ");
        inorder(T);
        printf("
    ");
    
        printf("postorder:   ");
        postorder(T);
        printf("
    ");
    
    
        printf("preorder(no_recersive):    ");
        preorder1(T);
        printf("
    
    ");
    
        printf("inorder(no_recersive):     ");
        inorder1(T);
        printf("
    
    ");
    
        return 0;
    }
  • 相关阅读:
    [转]: 浅谈Java中的equals和==
    易忘易混的java基本概念
    mysql查看锁表锁进程
    [转] Python 包管理工具解惑
    双网卡单网关的路由问题
    [转]火狐 SSL 收到了一个弱临时 Diffie-Hellman 密钥
    Linux中如何进入减号开头的目录中
    zabbix的一点记录
    从图形界面配置zabbix
    调用API自动配置zabbix version 3.0
  • 原文地址:https://www.cnblogs.com/TWS-YIFEI/p/5794806.html
Copyright © 2011-2022 走看看