C语言实现二叉查找树的插入与中序遍历

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

//二叉查找树的节点
struct bst_node {
    int value;
    struct bst_node *left;
    struct bst_node *right;
};

typedef struct bst_node Bst_Node;
typedef struct bst_node *P_Bst_Node;
typedef struct bst_node *Bin_Search_Tree;
typedef struct bst_node **P_Bin_Search_Tree;

void clear_bst(P_Bin_Search_Tree);

void insert_bst(P_Bin_Search_Tree, int);

void print_bst(Bin_Search_Tree);

int main() {
    printf("Hello, World!\n");
    char a[3][4];
    char b = 'a';
    int i, j;
    for (i = 0; i < 3; ++i) {
        for (j = 0; j < 4; ++j) {
            a[i][j] = (char) b++;
        }
    }
    for (i = 0; i < 3; ++i) {
        for (j = 0; j < 4; ++j) {
            printf("%c ", a[i][j]);
        }
        printf("\n");
    }
    printf("\n");
    char (*pc)[4];
    char *pd;
    for (i = 0, pc = a; i < 3; ++i) {
        for (j = 0, pd = *(pc + i); j < 4; ++j) {
            printf("%c ", *(pd + j));
        }
        printf("\n");
    }
    printf("\n");

    Bin_Search_Tree bst = NULL;
    P_Bin_Search_Tree p_bst = &bst;
    insert_bst(p_bst, 1);
    insert_bst(p_bst, 2);
    insert_bst(p_bst, 3);
    insert_bst(p_bst, 0);
    print_bst(bst);
    return 0;
}

void clear_bst(P_Bin_Search_Tree pt) {
    P_Bst_Node pn = *pt;
    if (pn != NULL) {
        clear_bst(&pn->left);
        clear_bst(&pn->right);
        free(pn);
        pn = NULL;
    }
}

void insert_bst(P_Bin_Search_Tree pt, int value) {
    if (*pt == NULL) {
        P_Bst_Node pn = malloc(sizeof(Bst_Node));
        pn->value = value;
        pn->left = pn->right = NULL;
        *pt = pn;
        return;
    }
    if (value < (*pt)->value) insert_bst(&(*pt)->left, value);
    else if (value > (*pt)->value) insert_bst(&(*pt)->right, value);
    else;
}

void print_bst(Bin_Search_Tree tree) {
    if (tree == NULL) return;
    print_bst(tree->left);
    printf("%d ", tree->value);
    print_bst(tree->right);
}

缺陷:暂 支持重复值的插入。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值