0

我有以下用于实现 BinarySearchTree 的代码。不知何故,它没有构建二叉树。任何人都可以帮助解决问题吗?

typedef struct BinarySearchTree

{

    struct BinarySearchTree *left;
    int nodeval;
    struct BinarySearchTree *right;

} 
BST;

BST *root=NULL;

void addrootnode(BST *,int );

void addnode(BST *,int );

void deletenode(int );

void printnodes();

main()

{

    int nodeval;
    char choice;
    printf("\n r->rootnode \n a->add \n d->delete \n p->print \n e->exit\n");
    while (1)
    {   
        printf("\nEnter your choice:");
        scanf("%c",&choice);
        switch (choice)
        {
        case 'r':
            printf("\nEnter the root node value to add: ");
            scanf("%d",&nodeval);
            addrootnode(root,nodeval);
            break;
        case 'a':
            printf("\nEnter the node value to add: ");
            scanf("%d",&nodeval);
            addnode(root,nodeval);
            break;
        case 'd':
            printf("\nEnter the node value to delete: ");
            scanf("%d",&nodeval);
            break;
        case 'p':
            //printf("\n");
            printnodes(root);
            break;
        case 'e':           
            exit(0);
        default:
            break;
        }
    }
    getchar();

}//end of main

//addrootnode

void addrootnode(BST *ptr,int num)

{

    if(ptr==NULL)
    {
        ptr=(BST *) malloc(sizeof(BST));
        ptr->left=NULL;
        ptr->nodeval=num;   
        ptr->right=NULL;        
        root=ptr;       
    }
}
//add node

void addnode(BST *ptr,int num)
{

    if(ptr==NULL)
    {
        ptr=(BST *) malloc(sizeof(BST));
        ptr->left=NULL;
        ptr->nodeval=num;   
        ptr->right=NULL;        


    }
    else if(num < ptr->nodeval )
    {       
        addnode(ptr->left,num);
    }
    else
    {

        addnode(ptr->right,num);
    }

}

//delete functionality

void deletenode(int nodeval)
{
}

//print all nodes

void printnodes(BST *ptr)

{

    if (ptr)

    {
        printnodes(ptr->left);
        printf("%d\t",ptr->nodeval);
        printnodes(ptr->right);
    }

}
4

1 回答 1

1

您不应将BST *ptr其用作 addnode 的参数。您尝试为其分配一个值,但此时它ptr是函数 addnode 的局部变量,不会改变父节点的预期左或右指针。

尝试考虑改用 BST **ptr。

于 2013-01-06T06:46:51.440 回答