在C++中,可以通過定義一個樹節點結構體來表示樹節點,并編寫插入和刪除操作的函數來實現對樹節點的操作。以下是一個簡單的示例:
#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);
// 輸出樹的節點值
std::cout << root->val << " " << root->left->val << " " << root->right->val << std::endl;
return 0;
}
在上面的示例中,定義了一個TreeNode
結構體來表示樹節點,然后實現了插入和刪除操作的函數insert
和remove
。在main
函數中創建了一個根節點,并依次插入一些節點值,然后刪除一個節點值,并輸出樹的節點值。