Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

แปลง Binary Tree เป็น Mirror Tree ใน C++


ในบทช่วยสอนนี้ เราจะพูดถึงโปรแกรมแปลง Binary Tree ให้กลายเป็น Mirror Tree (ต้นไม้กระจก)

เราจะได้รับ Binary Tree มา 1 ต้น งานคือสลับค่าทางซ้ายและขวา เพื่อสร้าง Mirror Tree จาก Binary Tree ที่ให้มา

ตัวอย่างโค้ด

#include <bits/stdc++.h>
using namespace std;

// โครงสร้างโหนด Binary Tree
struct Node {
    int data;
    struct Node* left;
    struct Node* right;
};

// สร้างโหนดใหม่ที่ไม่มีลูก
struct Node* newNode(int data) {
    struct Node* node = (struct Node*)malloc(sizeof(struct Node));
    node->data = data;
    node->left = NULL;
    node->right = NULL;
    return(node);
}

void mirror(struct Node* node) {
    if (node == NULL)
        return;
    else {
        struct Node* temp;
        // สลับ Subtree
        mirror(node->left);
        mirror(node->right);
        temp = node->left;
        node->left = node->right;
        node->right = temp;
    }
}

// พิมพ์การท่อง Inorder
void print_tree(struct Node* node) {
    if (node == NULL)
        return;
    print_tree(node->left);
    cout << node->data << " ";
    print_tree(node->right);
}

int main() {
    struct Node* root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(3);
    root->left->left = newNode(4);
    root->left->right = newNode(5);

    // พิมพ์ต้นไม้ต้นฉบับ
    cout << "Inorder traversal of the constructed" << endl;
    print_tree(root);

    mirror(root);

    // พิมพ์ Mirror Tree
    cout << "\nInorder traversal of the mirror tree" << endl;
    print_tree(root);
    return 0;
}

ผลลัพธ์

Inorder traversal of the constructed 4 2 5 1 3
Inorder traversal of the mirror tree 3 1 5 2 4