c++编写二叉树的基本操作
时间: 2023-08-06 15:07:41 浏览: 76
二叉树的基本操作包括创建、插入、删除、查找、遍历等,下面是C++代码示例:
```cpp
#include <iostream>
#include <queue>
using namespace std;
// 定义二叉树节点的结构体
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
// 创建二叉树
TreeNode* createTree() {
int val;
cin >> val;
if (val == -1) {
return nullptr;
}
TreeNode* root = new TreeNode(val);
root->left = createTree();
root->right = createTree();
return root;
}
// 插入节点
void insertNode(TreeNode* root, int val) {
if (root == nullptr) {
return;
}
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
TreeNode* cur = q.front();
q.pop();
if (cur->left == nullptr) {
cur->left = new TreeNode(val);
return;
}
if (cur->right == nullptr) {
cur->right = new TreeNode(val);
return;
}
q.push(cur->left);
q.push(cur->right);
}
}
// 删除节点
TreeNode* deleteNode(TreeNode* root, int val) {
if (root == nullptr) {
return nullptr;
}
if (root->val == val) {
if (root->left == nullptr && root->right == nullptr) {
delete root;
return nullptr;
}
if (root->left == nullptr) {
TreeNode* temp = root->right;
delete root;
return temp;
}
if (root->right == nullptr) {
TreeNode* temp = root->left;
delete root;
return temp;
}
TreeNode* minNode = root->right;
while (minNode->left != nullptr) {
minNode = minNode->left;
}
root->val = minNode->val;
root->right = deleteNode(root->right, minNode->val);
} else if (root->val > val) {
root->left = deleteNode(root->left, val);
} else {
root->right = deleteNode(root->right, val);
}
return root;
}
// 查找节点
TreeNode* searchNode(TreeNode* root, int val) {
if (root == nullptr || root->val == val) {
return root;
}
if (root->val > val) {
return searchNode(root->left, val);
} else {
return searchNode(root->right, val);
}
}
// 前序遍历
void preOrder(TreeNode* root) {
if (root == nullptr) {
return;
}
cout << root->val << " ";
preOrder(root->left);
preOrder(root->right);
}
// 中序遍历
void inOrder(TreeNode* root) {
if (root == nullptr) {
return;
}
inOrder(root->left);
cout << root->val << " ";
inOrder(root->right);
}
// 后序遍历
void postOrder(TreeNode* root) {
if (root == nullptr) {
return;
}
postOrder(root->left);
postOrder(root->right);
cout << root->val << " ";
}
int main() {
// 创建二叉树
TreeNode* root = createTree();
// 插入节点
insertNode(root, 10);
// 删除节点
root = deleteNode(root, 5);
// 查找节点
TreeNode* node = searchNode(root, 3);
cout << "search node: " << node->val << endl;
// 遍历二叉树
cout << "preorder: ";
preOrder(root);
cout << endl;
cout << "inorder: ";
inOrder(root);
cout << endl;
cout << "postorder: ";
postOrder(root);
cout << endl;
return 0;
}
```
以上代码包含了二叉树的创建、插入、删除、查找以及前序、中序、后序遍历等基本操作。
阅读全文