天天看點

語言編寫二叉樹的代碼使用汽車品牌作為執行個體

作者:靈思緻遠IT學苑
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// 結構體定義
typedef struct node {
    char brand[20];
    struct node* left;
    struct node* right;
} TreeNode;

// 插入節點
void insert(TreeNode** node, char* brand) {
    if (*node == NULL) {
        // 建立新節點
        TreeNode* new_node = (TreeNode*)malloc(sizeof(TreeNode));
        strcpy(new_node->brand, brand);
        new_node->left = NULL;
        new_node->right = NULL;
        *node = new_node;
    }
    else {
        // 将小于等于目前節點的資料插入到左子樹中,大于目前節點的資料插入到右子樹中
        if (strcmp(brand, (*node)->brand) <= 0) {
            insert(&((*node)->left), brand);
        }
        else {
            insert(&((*node)->right), brand);
        }
    }
}

// 中序周遊
void inorder(TreeNode* node) {
    if (node != NULL) {
        inorder(node->left);
        printf("%s ", node->brand);
        inorder(node->right);
    }
}

// 先序周遊
void preorder(TreeNode* node) {
    if (node != NULL) {
        printf("%s ", node->brand);
        preorder(node->left);
        preorder(node->right);
    }
}

// 後序周遊
void postorder(TreeNode* node) {
    if (node != NULL) {
        postorder(node->left);
        postorder(node->right);
        printf("%s ", node->brand);
    }
}

// 釋放節點
void free_node(TreeNode* node) {
    if (node != NULL) {
        free_node(node->left);
        free_node(node->right);
        free(node);
    }
}

// 顯示菜單
void show_menu() {
    printf("\n");
    printf("1. 插入汽車品牌\n");
    printf("2. 中序周遊\n");
    printf("3. 先序周遊\n");
    printf("4. 後序周遊\n");
    printf("5. 退出程式\n");
    printf("\n");
}

int main() {
    TreeNode* root = NULL;
    int choice = 0;
    char brand[20];

    do {
        show_menu();
        printf("請輸入選項:");
        scanf("%d", &choice);

        switch (choice) {
        case 1:
            printf("請輸入汽車品牌:");
            scanf("%s", brand);
            insert(&root, brand);
            break;
        case 2:
            inorder(root);
            printf("\n");
            break;
        case 3:
            preorder(root);
            printf("\n");
            break;
        case 4:
            postorder(root);
            printf("\n");
            break;
        case 5:
            free_node(root);
            printf("程式已退出。\n");
            break;
        default:
            printf("無效的選項,請重新輸入。\n");
            break;
        }
    } while (choice != 5);

    return 0;
}
           

以上代碼實作了二叉樹的基本操作:插入、中序周遊、先序周遊、後序周遊。

繼續閱讀