码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-08-22 12:20:38      阅读:165      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!