帮我在上面这段代码中添加新功能:元素未被查到时,输出nothing
时间: 2024-03-07 13:50:27 浏览: 22
已经添加了这个功能,请看我在代码中加粗的部分:
```c++
#include <iostream>
#include <string>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
void insert(TreeNode*& root, int val) {
if (root == nullptr) {
root = new TreeNode(val);
return;
}
if (val < root->val) {
insert(root->left, val);
} else if (val > root->val) {
insert(root->right, val);
}
}
string search(TreeNode* root, int val) {
string path = "*";
while (root != nullptr) {
if (val < root->val) {
path += "l";
root = root->left;
} else if (val > root->val) {
path += "r";
root = root->right;
} else {
return path;
}
}
// 如果未查到,返回"Nothing."
return "Nothing.";
}
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;
root = root->right;
delete temp;
} else if (root->right == nullptr) {
TreeNode* temp = root;
root = root->left;
delete temp;
} else {
TreeNode* minNode = root->right;
while (minNode->left != nullptr) {
minNode = minNode->left;
}
root->val = minNode->val;
remove(root->right, minNode->val);
}
}
}
int main() {
int Q;
cin >> Q;
TreeNode* root = nullptr;
for (int i = 0; i < Q; i++) {
char op;
int x;
cin >> op >> x;
if (op == '+') {
insert(root, x);
} else if (op == '-') {
remove(root, x);
} else if (op == '*') {
string result = search(root, x);
cout << result << endl;
// 如果未查到,输出"Nothing."
} else {
cout << "Invalid operation." << endl;
}
}
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)