开发者

BST with a recursion and given structures

I have to code some methods for a BST and I have some problems, let me explain.

I have the following structures :

struct node {
    struct node *lChild; 
    struct node *rChild; 
    int value; 
};

and

struct tree {
    struct node *root;
};

along with the following functions :

struct tree* constructNewTree()
{
    struct tree *T=malloc(sizeof(struct tree));
    T->root=NULL;

    return T;
}

and

struct node* constructNewNode(int i)
{
    struct node *N=malloc(sizeof(struct node));
    N->value=i;
    N->lChild=NULL;
    N->rChild=NULL;

    return N;
}

And in my main I must call this (for example) :

int main()
{
    struct tree *T;
    T=constructNewTree();

    insertKey(5,T);
    insertKey(2,T);
    insertKey(9,T);
    return 0;
}

What I have to do is to create the function insertKey(int开发者_JAVA百科 i, struct tree *T) using the recursion.

I wanted to do something like

void insertKey(int i, struct tree *T)
{
    if (T->root==NULL) {
        T->root=constructNewNode(i);
        return;
    }
    else {
        if (i<=T->root->value) {
            T->root->lChild=constructNewNode(i);
        else if (i>T->root->value) {
            T->root->rChild=constructNewNode(i);
        }
    }
}

But it doesn't get very far, using the recursion would allow me to call insertKey again but I can't seem to use a node and a tree the same way.

Does anyone know how I could do that without altering the given structures?

Thank you very much.


Your insertKey takes a Tree as its argument. A Tree is only a pointer to the very top.

What I recommend you do is write a insertKey function that takes a Node for its argument. Also in this function, you have to check to see if there is another tree on the left/right child.

Currently you just construct a new node regardless of what is there. This will overwrite any previous insertions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜