二叉树排序查找代码c++
时间: 2023-08-06 10:05:44 浏览: 88
二叉树排序查找的代码如下所示:
```c++
#include<iostream>
using namespace std;
//定义二叉树结点
struct TreeNode{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL){}
};
//插入结点
TreeNode* insertNode(TreeNode* root, int val){
if(root == NULL){
return new TreeNode(val);
}
if(val < root->val){
root->left = insertNode(root->left, val);
}else{
root->right = insertNode(root->right, val);
}
return root;
}
//搜索结点
TreeNode* searchNode(TreeNode* root, int val){
if(root == NULL || root->val == val){
return root;
}
if(val < root->val){
return searchNode(root->left, val);
}else{
return searchNode(root->right, val);
}
}
//删除结点
TreeNode* deleteNode(TreeNode* root, int val){
if(root == NULL){
return root;
}
if(val < root->val){
root->left = deleteNode(root->left, val);
}else if(val > root->val){
root->right = deleteNode(root->right, val);
}else{
if(root->left == NULL){
TreeNode* temp = root->right;
delete root;
return temp;
}else if(root->right == NULL){
TreeNode* temp = root->left;
delete root;
return temp;
}else{
TreeNode* temp = root->right;
while(temp->left != NULL){
temp = temp->left;
}
root->val = temp->val;
root->right = deleteNode(root->right, temp->val);
}
}
return root;
}
//中序遍历
void inorderTraversal(TreeNode* root){
if(root == NULL){
return;
}
inorderTraversal(root->left);
cout << root->val << " ";
inorderTraversal(root->right);
}
int main(){
TreeNode* root = NULL;
root = insertNode(root, 10);
insertNode(root, 5);
insertNode(root, 15);
insertNode(root, 3);
insertNode(root, 8);
insertNode(root, 12);
insertNode(root, 20);
cout << "中序遍历结果为:";
inorderTraversal(root);
cout << endl;
TreeNode* node = searchNode(root, 12);
if(node != NULL){
cout << "查找到结点:" << node->val << endl;
}else{
cout << "未找到该结点!" << endl;
}
root = deleteNode(root, 15);
cout << "删除15后中序遍历结果为:";
inorderTraversal(root);
cout << endl;
return 0;
}
```
这段代码实现了二叉树排序查找的基本操作,包括插入结点、搜索结点、删除结点以及中序遍历等。其中,`insertNode`函数用于插入结点,`searchNode`函数用于搜索结点,`deleteNode`函数用于删除结点,`inorderTraversal`函数用于中序遍历二叉树。
阅读全文