cyg41223103 cp2023

  • Home
    • SMap
    • reveal
    • blog
  • About
  • Brython
  • w15
    • Q2
    • Q1
  • 作業內容
    • W3
    • W4
    • w5
    • w6
      • 台灣國旗
      • 日本國旗
      • 美國國旗
      • 英國國旗
      • 韓國國旗
      • 中國國旗
    • W7
    • W10
    • W13
  • ANSI C
    • c1.
    • c2.
    • c3.
    • c4.
    • c5.
    • c6.
    • c7.
    • c8.
    • c9.
    • c10.
  • C_EX
    • ex1.
    • ex2.
    • ex3.
    • ex4.
    • ex5.
    • ex6.
    • ex7.
    • ex8.
    • ex9.
    • ex10.
  • NOTE
    • ssh
c6. << Previous Next >> c8.

c7.

鏡像的二元樹鏡像

// 包括必要的頭文件
#include <stdio.h>
#include <stdlib.h>
 
// 二元樹節點的結構
struct TreeNode {
    int data;
    struct TreeNode* left;
    struct TreeNode* right;
};
 
// 建立新節點的函數
struct TreeNode* createNode(int value) {
    struct TreeNode* newNode = (struct TreeNode*)malloc(sizeof(struct TreeNode));
    if (newNode != NULL) {
        newNode->data = value;
        newNode->left = NULL;
        newNode->right = NULL;
    }
    return newNode;
}
 
// 向二元樹插入節點的函數
struct TreeNode* insertNode(struct TreeNode* root, int value) {
    if (root == NULL) {
        return createNode(value);
    }
 
    if (value < root->data) {
        root->left = insertNode(root->left, value);
    } else if (value > root->data) {
        root->right = insertNode(root->right, value);
    }
 
    return root;
}
 
// 執行有序遍歷和列印元素的函數
void inOrderTraversal(struct TreeNode* root) {
    if (root != NULL) {
        inOrderTraversal(root->left);
        printf("%d ", root->data);
        inOrderTraversal(root->right);
    }
}
 
// 建立二元樹鏡像的函數
struct TreeNode* mirrorTree(struct TreeNode* root) {
    if (root == NULL) {
        return NULL;
    }
 
    // 交換左右子樹
    struct TreeNode* temp = root->left;
    root->left = mirrorTree(root->right);
    root->right = mirrorTree(temp);
 
    return root;
}
 
// 釋放為二元樹分配的記憶體的函數
void freeTree(struct TreeNode* root) {
    if (root != NULL) {
        freeTree(root->left);
        freeTree(root->right);
        free(root);
    }
}
 
int main() {
    struct TreeNode* root = NULL;
    int nodeValue;
    char choice;
 
    // 將節點插入二元樹
    do {
        printf("Input a value to insert into the binary tree (enter 0 to stop): ");
        scanf("%d", &nodeValue);
 
        if (nodeValue != 0) {
            root = insertNode(root, nodeValue);
        }
 
    } while (nodeValue != 0);
 
    //列印原始二元樹
    printf("\nOriginal Binary Tree (In-order Traversal): ");
    inOrderTraversal(root);
    printf("\n");
 
    // 建立並列印二元樹的鏡像
    struct TreeNode* mirroredRoot = mirrorTree(root);
    printf("\nMirrored Binary Tree (In-order Traversal): ");
    inOrderTraversal(mirroredRoot);
    printf("\n");
 
    // 釋放分配的記憶體
    freeTree(root);
    freeTree(mirroredRoot);
 
    return 0;
}


c6. << Previous Next >> c8.

Copyright © All rights reserved | This template is made with by Colorlib