why this function not work in create BinTree

59 views Asked by At

I want create this BinTree .enter image description here in this function it can't work.

typedef struct BinNode {
    Elemtype data;
    struct BinNode* left;
    struct BinNode* right;
}BinNode,*BinTree;
void createBinTree(BinTree* root, char* a) {
    if (*a == '\0')
        return;
    if (*a == '#') {
        (*root) = NULL;
        return;
    }
    else {
        (*root) = (BinTree)malloc(sizeof(BinNode));
        assert((*root) != NULL);
        (*root)->data = *a;
        createBinTree(&(*root)->left, ++a);
        createBinTree(&(*root)->right, ++a);
        return;
    }

}
int main() {
    char* ptr = "ABC##DE##F##G#H##";
    BinTree my_tree = NULL;
    createBinTree(&my_tree,ptr);
    return 0;
}

I try to run this function,It doesn't create the correct BinTree like in the picture。 but this way can.

void createBinTree(BinTree* root, char** a) {
    if (**a == '\0')
        return;
    if (**a == '#') {
        (*root) = NULL;
        (*a)++;
        return;
    }
    else {
        (*root) = (BinTree)malloc(sizeof(BinNode));
        assert((*root) != NULL);
        (*root)->data = **a;
        (*a)++;
        createBinTree(&(*root)->left, a);
        createBinTree(&(*root)->right, a);
        return;
    }
}
int main() {
    char* ptr = "ABC##DE##F##G#H##";
    BinTree my_tree = NULL;
    createBinTree(&my_tree,&ptr);
    return 0;
}

why it can. i don't understand why call createBinTree need pass &ptr but **ptr.**please help me!

1

There are 1 answers

3
Vlad from Moscow On

In the first program the value of the pointer a in the second call of the function

createBinTree(&(*root)->right, ++a);

is not equal to the last value of the pointer a after the first call of the function

createBinTree(&(*root)->left, ++a);

Consider for example the initial processing of the string.

In the first call of the function there is passed the pointer a that points to the character 'B'.

In the second call of the function there is passed the pointer a that points to the character 'C' instead of pointing to the character '#'.

In the second program the pointer a is passed by reference through a pointer to it. So after the first call of the function the value of the pointer a will be the last value of the pointer after the first function call.