用C++实现请根据输入的数据创建一棵二叉排序树。然后执行相应操作。 1 删除某一值为x的结点 2 求指定结点y在二叉排序树中的层数
时间: 2024-02-13 10:04:23 浏览: 59
好的,我可以为您提供相关的C++代码。请注意,这里的代码是基于命令行输入,您可以在代码中根据需要进行修改。
```c++
#include<iostream>
using namespace std;
// 定义树结点
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
// 插入新结点
TreeNode* insert(TreeNode* root, int val) {
if (root == NULL) {
return new TreeNode(val);
}
if (val < root->val) {
root->left = insert(root->left, val);
}
else {
root->right = insert(root->right, val);
}
return root;
}
// 删除指定结点
TreeNode* deleteNode(TreeNode* root, int val) {
if (root == NULL) {
return NULL;
}
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) {
return root->right;
}
else if (root->right == NULL) {
return root->left;
}
TreeNode* minNode = root->right;
while (minNode->left != NULL) {
minNode = minNode->left;
}
root->val = minNode->val;
root->right = deleteNode(root->right, minNode->val);
}
return root;
}
// 查找指定结点的层数
int findLevel(TreeNode* root, int val) {
if (root == NULL) {
return -1;
}
if (root->val == val) {
return 0;
}
if (val < root->val) {
int level = findLevel(root->left, val);
if (level == -1) {
return -1;
}
else {
return level + 1;
}
}
else {
int level = findLevel(root->right, val);
if (level == -1) {
return -1;
}
else {
return level + 1;
}
}
}
int main() {
TreeNode* root = NULL;
// 输入数据,构建二叉排序树
int n;
cin >> n;
for (int i = 0; i < n; i++) {
int val;
cin >> val;
root = insert(root, val);
}
// 删除指定结点
int x;
cin >> x;
root = deleteNode(root, x);
// 查找指定结点的层数
int y;
cin >> y;
int level = findLevel(root, y);
if (level == -1) {
cout << "Node " << y << " not found in the tree." << endl;
}
else {
cout << "Node " << y << " is at level " << level << " in the tree." << endl;
}
return 0;
}
```
希望这段代码能够帮助您实现所需的功能。
阅读全文