#include <iostream>
using namespace std;
struct Node {
int data; // Value of the node
Node* left; // Pointer to the left
Node* right; // Pointer to the right
};
Node* create(int data) {
Node* temp = new Node();
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return temp;
}
void insert(Node* &root , int data) {
if(root == NULL) {
root = create(data);
}
else if(root->data > data) {
insert(root->left, data);
}
else {
insert(root->right, data);
}
}
void print(Node* root) {
if(root != NULL) {
print(root->left);
cout << root->data << " ";
print(root->right);
}
}
int main() {
Node* root = NULL;
int number;
int value;
cout << "How many nodes do you want to insert: ";
cin >> number;
for(int i = 0; i < number; i++) {
cin >> value;
insert(root, value);
}
print(root);
}
我正在学习如何实现BST,并对insert函数有疑问。无效插入(Node *&root,int data)为什么会有&之前的根?我的猜测是有一个&,因为我们正在修改树,但我不太确定。
谢谢!
为什么在根之前有&?