简体   繁体   中英

Binary Search Tree Program says root does not name a type

I am trying to execute the binary search tree on my C++ compiler but when i input the following code on the compiler i get the error saying 9 [Error] 'root' does not name a type and 19 [Error] expected unqualified-id before '{' token.I tried changing the pointer root to integer but it gives a conversion error.

#include<iostream>
using namespace std;
struct bstnode{
    int data;
    bstnode*left;
    bstnode*right;
};
bstnode* root;
root = 0;
bstnode*getnewnode(int data)
{
    bstnode* newnode=new bstnode();
    newnode->data=data;
    newnode->left=newnode->right=NULL;
    return newnode;

}
void insert(bstnode*root,int data);
{
    {

    if(root==NULL)
    root=getnewnode(data);

}
else if(data<=root->data)
{
    root->left=insert(root->left,data);
}
else
{
    root->right=insert(root->right,root);
}
return root;
}
bool search(bstnode*root,int data)
{
    if(root==NULL) return false;
    else if(root->data=data) return true;
    else if(data<=root->data) return search(root->left,data);
    else return search(root->right,data);
}
int main()
{
    bstnode*root=NULL;
    root=insert(root,15);
    root=insert(root,10);
    root=insert(root,12);
    int number;
    cout<<"enter no";
    cin>>no;


}

tag is removed, so this part is not relevant now.

In your code, `bstnode` is **not** a type. You need to either - Alias (mimic) a type by using `typedef` - use `struct bstnode`

That said, ( considering bstnode is a valid type )

bstnode* root;
root = 0;

is wrong, you cannot have an assignment statement in file scope, you need to use an initializer, like

bstnode* root = NULL;

After that, it looks like, you're not using that global variable, at all.

Inside main() , you have a function scope variable root which shadows the global variable, and you pass that inner scope variable to the called functions, so the global variable is not utilized or rather needed, at all. Get rid of that.

The "top" file level can only contain declarations and definitions, but you have an assignment there:

bstnode* root;
root = 0;

Remove those lines; you're not using that variable.

You need to define the bstnode* root = NULL; rather than the way you did above

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM