Home > AI > Uncategorized

数的创建和三种遍历

#include <stdio.h>
#include <stdlib.h>


struct node
{
    char data;
    struct node* lchild;
    struct node* rchild;
};


struct node* create()
{
    struct node* temp;
    int ch;
    temp = (struct node*)malloc(sizeof(struct node));
    
    printf("input data\n");
    scanf("%c", &temp->data);
    setbuf(stdin, NULL); //clean buf
    
    printf("is left child(1/0)\n");
    scanf("%d", &ch);
    setbuf(stdin, NULL);
    if (ch == 1)
        temp->lchild = create();
    else
        temp->lchild = NULL;
    
    printf("is right child(1/0)\n");
    scanf("%d", &ch);
    setbuf(stdin, NULL);
    if (ch == 1)
        temp->rchild = create();
    else
        temp->rchild = NULL;

    
    return temp;
}


void preorder(struct node* root)
{
    if (root == NULL)
    {
        return;
    } else {
        printf("%c\t", root->data);
        preorder(root->lchild);
        preorder(root->rchild);
    }
    
}


void inorder(struct node* root)
{
    if (root == NULL)
    {
        return;
    } else {
        inorder(root->lchild);
        printf("%c\t", root->data);
        inorder(root->rchild);
    }
}


void postorder(struct node* root)
{
    if (root == NULL)
    {
        return;
    } else {
        postorder(root->lchild);
        postorder(root->rchild);
        printf("%c\t", root->data);
    }
}


int main(int argc, char* argv[])
{
    struct node* root = (struct node*)malloc(sizeof(struct node));
    root = create();
    
    printf("preorder:\n");
    preorder(root);
    
    printf("inorder:\n");
    inorder(root);
    
    printf("postorder:\n");
    postorder(root);
    
}

 

Related posts:

Leave a Reply