使用单链接列表实现BinarySearchTree

时间:2013-01-06 06:41:56

标签: c algorithm data-structures binary-tree

我有以下代码用于实现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);
    }

}

1 个答案:

答案 0 :(得分:1)

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

尝试考虑使用BST ** ptr。