首页 > 其他 > 详细

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

时间:2016-08-22 12:17:55      阅读:146      评论:0      收藏:0      [点我收藏+]

 

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

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);
    }
}

//非递归先序遍历



//非递归中序遍历

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");
    return 0;
}

 

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

原文:http://www.cnblogs.com/TWS-YIFEI/p/5794806.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!