Shark Deng

Interactive Designer @Shanju Design in Shanghai

touched caffe / mxnet / python / wordpress / bootstrap / Arduino / Raspberry Pi / webgl / three.js / PIXI / 3dMax

Email

Github

数的创建和三种遍历

2019-11-13 00:16:02

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

 



——By SharkDeng
如果你喜欢我的文章,欢迎红包赞赏

Leave a Reply

Your email address will not be published. Required fields are marked *