二叉树的创建和三种遍历(先序、中序和后序)

   这两天清明放假,学习效率很低,二叉树的创建中指针的使用让我颇为不爽,我对指针的理解仍是肤浅。
php

待解决的问题:node

http://bbs.51cto.com/viewthread.php?tid=1103326&extra=page%3D1&frombbs=1linux

   还望高人指点迷津。编程

  二叉树的存储使用二叉链表结构:ide

typedef struct node{
    char data;
    struct node *lchild, *rchild;
}btree, *bitree;

(我在学习linux C编程,因此编程风格倾向于linxu c编程风格。)post

下面是所有代码:学习

#include<malloc.h>
#include<stdio.h>
typedef struct node{
    char data;
    struct node *lchild, *rchild;
}btree, *bitree;
//先序遍历二叉树
void  preorder(bitree root)
{
    if(root)
    {
        printf("%3c", root->data);
        preorder(root->lchild);
        preorder(root->rchild);
    }
}
//中序遍历二叉树
int inorder(bitree root)
{
    if(root)
    {
        inorder(root->lchild);
        printf("%3c", root->data);
        inorder(root->rchild);
    }
}
//后序遍历二叉树
void postorder(bitree root)
{
    if(root)
    {
        postorder(root->lchild);
        postorder(root->rchild);
        printf("%3c", root->data);
    }
}
//构造二叉树
void create_tree(bitree *root)
{
    char c;
    c = getchar();
    if(c == '.')
        *root = NULL;
    else{
        *root = (bitree)malloc(sizeof(btree));
        (*root)->data = c;
        create_tree(&(*root)->lchild);
        create_tree(&(*root)->rchild); 
    }
                                              
}
int main()
{ 
    bitree tree;
    printf("enter you tree \n");
    create_tree(&tree);
    printf("create done\n");
    printf("  preorder start: ");
    preorder(tree);
    printf("  preorder end\n");
    printf("  inorder start: ");
    inorder(tree);
    printf("  inorder end\n");
    printf("  postorder start: ");
    postorder(tree);  
    printf("  postorder end\n");
    return 0;
}
相关文章
相关标签/搜索