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

缺陷:暫 支持重複值的插入。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章