C++中樹節(jié)點(diǎn)的插入與刪除操作

c++
小樊
85
2024-08-24 03:23:30

在C++中,可以通過(guò)定義一個(gè)樹節(jié)點(diǎn)結(jié)構(gòu)體來(lái)表示樹節(jié)點(diǎn),并編寫插入和刪除操作的函數(shù)來(lái)實(shí)現(xiàn)對(duì)樹節(jié)點(diǎn)的操作。以下是一個(gè)簡(jiǎn)單的示例:

#include <iostream>

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;

    TreeNode(int v) : val(v), left(nullptr), right(nullptr) {}
};

void insert(TreeNode* root, int val) {
    if (root == nullptr) {
        root = new TreeNode(val);
    } else if (val < root->val) {
        if (root->left == nullptr) {
            root->left = new TreeNode(val);
        } else {
            insert(root->left, val);
        }
    } else {
        if (root->right == nullptr) {
            root->right = new TreeNode(val);
        } else {
            insert(root->right, val);
        }
    }
}

void remove(TreeNode* root, int val) {
    if (root == nullptr) {
        return;
    }
    if (val < root->val) {
        remove(root->left, val);
    } else if (val > root->val) {
        remove(root->right, val);
    } else {
        if (root->left == nullptr) {
            TreeNode* temp = root->right;
            delete root;
            root = temp;
        } else if (root->right == nullptr) {
            TreeNode* temp = root->left;
            delete root;
            root = temp;
        } else {
            TreeNode* minNode = root->right;
            while (minNode->left != nullptr) {
                minNode = minNode->left;
            }
            root->val = minNode->val;
            remove(root->right, minNode->val);
        }
    }
}

int main() {
    TreeNode* root = new TreeNode(5);
    insert(root, 3);
    insert(root, 7);
    insert(root, 2);
    insert(root, 4);
    insert(root, 6);
    insert(root, 8);

    remove(root, 3);

    // 輸出樹的節(jié)點(diǎn)值
    std::cout << root->val << " " << root->left->val << " " << root->right->val << std::endl;

    return 0;
}

在上面的示例中,定義了一個(gè)TreeNode結(jié)構(gòu)體來(lái)表示樹節(jié)點(diǎn),然后實(shí)現(xiàn)了插入和刪除操作的函數(shù)insertremove。在main函數(shù)中創(chuàng)建了一個(gè)根節(jié)點(diǎn),并依次插入一些節(jié)點(diǎn)值,然后刪除一個(gè)節(jié)點(diǎn)值,并輸出樹的節(jié)點(diǎn)值。

0