C语言二叉树操作

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

typedef struct BTNode
{
    char data;
    struct BTNode *lChild;
    struct BTNode *rChild;
} BTNODE, *BTREE;

BTREE create();

void preOrder(BTREE);
void inOrder(BTREE);
void postOrder(BTREE);

void preOrder1(BTREE);
void inOrder1(BTREE);
void postOrder1(BTREE);

int main(void)
{
    printf("请输入根结点:");
    BTREE bt = create();
    printf("\n先序遍历为:");
    preOrder(bt);
    printf("\n中序遍历为:");
    inOrder(bt);
    printf("\n后序遍历为:");
    postOrder(bt);
    return 0;
}

BTREE create()
{
    int val;
    scanf("%d", &val);
    if (val <= 0)
    {
        return NULL;
    }
    BTREE bt = (BTREE)malloc(sizeof(BTNODE));
    if (!bt)
    {
        printf("创建失败\n");
    }
    bt->data = val;
    printf("请输入%d的左孩子结点:", val);
    bt->lChild = create();
    printf("请输入%d的右孩子结点:", val);
    bt->rChild = create();
    return bt;
}

void preOrder(BTREE bt)
{
    if (bt == NULL)
    {
        return;
    }
    printf("%d ", bt->data);
    preOrder(bt->lChild);
    preOrder(bt->rChild);
}
void inOrder(BTREE bt)
{
    if (bt == NULL)
    {
        return;
    }
    inOrder(bt->lChild);
    printf("%d ", bt->data);
    inOrder(bt->rChild);
}
void postOrder(BTREE bt)
{
    if (bt == NULL)
    {
        return;
    }
    postOrder(bt->lChild);
    postOrder(bt->rChild);
    printf("%d ", bt->data);
}

//非递归方式遍历
void preOrder1(BTREE bt)
{
    BTREE stack[15];
    int top = -1;
    BTREE root = bt;
    while (root != NULL || top != -1)
    {
        if (root != NULL)
        {
            stack[++top] = root;
            printf("%d ", root->data);
            root = root->lChild;
        }
        else
        {
            root = stack[top--];
            root = root->rChild;
        }
    }
}

void inOrder1(BTREE bt)
{
    BTREE stack[15];
    int top = -1;
    BTREE root = bt;
    while (root != NULL || top != -1)
    {
        if (root != NULL)
        {
            stack[++top] = root;
            root = root->lChild;
        }
        else
        {
            root = stack[top--];
            printf("%d ", root->data);
            root = root->rChild;
        }
    }
}

void postOrder1(BTREE bt)
{
    BTREE stack[15];
    BTREE stack1[15];
    int top = -1;
    int i = -1;
    BTREE root = bt;
    stack[++top] = root;
    while (top != -1)
    {
        root = stack[top--];
        stack1[++i] = root;
        if (root->lChild != NULL)
        {
            stack[++top] = root->lChild;
        }
        if (root->rChild != NULL)
        {
            stack[++top] = root->rChild;
        }
    }
    while (i != -1)
    {
        printf("%d ", stack1[i--]->data);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值