将有序链表转换为二叉搜索树

时间:2013-09-25 16:15:10

标签: c linked-list binary-search-tree

这是我的代码。请让我知道这个错误。问题是将给定的有序链表转换为二叉搜索树。

感谢。

struct treenode* makeBSTnode(struct node* head)
{
    struct treenode *root=(struct treenode*)malloc(sizeof(struct treenode));
    root->data = head->data;
    root->leftchild = NULL;
    root->rightchild = NULL;
    return root;
}


struct treenode* makeBST(struct node **head,int iterations)
{
    if(iterations==0)
    {
        /*this is the code for the base condition*/    
        struct treenode *root=(struct treenode*)malloc(sizeof(struct treenode));
        root = makeBSTnode(*head);
        return root;
    }
    else
    {
        /*this is for the case when the node is not single but should be broken down into parts*/
        struct node *leftchildnode=NULL,*rightchildnode=NULL,*rootnode=NULL,*temp;
        temp = (struct node*)malloc(sizeof(struct node));
        struct treenode *root = (struct treenode*)malloc(sizeof(struct treenode)); 
        int limit = (int)ceil((float)(3*iterations)/2);
        for(int i=1;i<=limit;i++)
        {
            if(i==(int)ceil((float)iterations/2))
            {
                leftchildnode = (struct node*)malloc(sizeof(struct node));
                leftchildnode = *head;
            }
            else if(i==iterations)
            {
                rootnode = (struct node*)malloc(sizeof(struct node));
                rootnode = *head;
            }
            else if(i==(int)ceil((float)(3*iterations)/2))
            {
                rightchildnode = (struct node*)malloc(sizeof(struct node));
                rightchildnode = *head;
            }
            if(*head)
            (*head) = (*head)->next;
            else
            break;
        }
        root = makeBSTnode(rootnode);
        root->leftchild = makeBST(&temp,(int)ceil((float)iterations/2));
        root->rightchild = makeBST(&rootnode,(int)ceil((float)(3*iterations/2)));
        return root;
    }
}

我在main中调用了makeBST函数: root = makeBST(&amp; head,(int)ceil((float)length / 2));

0 个答案:

没有答案