我正在尝试编写从排序数组创建BST的代码。这是我到目前为止得到的代码:
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *left;
Node *right;
Node (int v) {
data = v;
left = right = NULL;
}
}
Node* createBST(int arr[], int start, int end) {
if (end <= start)
return NULL;
int mid = (start+end)/2;
Node* root = new Node(arr[mid]);
root->left = createBST(arr, start, mid);
root->right = createBST(arr, mid+1, end);
return root;
}
void inorder(Node* root) {
if (root == NULL)
return;
inorder(root->left);
cout<<root->data<<" ";
inorder(root->right);
}
int main() {
int t, n, i;
cin>>t;
while (t--) {
cin>>n;
int arr[n];
for (i=0; i<n; i++)
cin>>arr[i];
Node* root = createBST(arr, 0, n);
inorder(root);
cout<<endl;
}
return 0;
}
我在其中编写此代码的GeeksforGeeks沙箱会抛出以下错误:
Compilation Error:
prog.cpp:14:5: error: expected initializer before * token
Node* createBST(int arr[], int start, int end) {
^
prog.cpp: In function int main():
prog.cpp:40:38: error: createBST was not declared in this scope
Node* root = createBST(arr, 0, n);
^
我不知道我做错了什么。
结构节点{。。。}
后面需要一个分号。否则,以下内容将被视为具有node
类型的变量。
struct Node {
int data;
Node *left;
Node *right;
Node (int v) {
data = v;
left = right = NULL;
}
}; // <- add a semicolon here