i wrote a simple program to sort numbers one by one for their repeat time and then inserts them one by one to tree. My problem is, i couldn’t insert root’s children because i couldn’t change the function below to call-by-reference type.
q parameter below needs to hold the root’s address value i think.
void insertNode(int data, node *q, node *parent){
if(q == NULL){
node *p = createNode(data);
p -> parent = parent;
p -> key = generateKey(p);
int i;
for(i = 0;table[i][1] != 0;i++);
table[i][1] = p -> data;
table[i][0] = p -> key;
q = p;
}
else if(q -> left > q -> right || q -> left == q -> right){
q -> right++;
insertNode(data, q -> rightChild, q);
}
else if(q -> right > q -> left){
q -> left++;
insertNode(data, q -> leftChild, q);
}
}
The node allocated in the “if(q == NULL){
}” block is lost; once the function returns, there is no pointer to it available to the caller. (the q=p; assignment does nothing)
UPDATE: the **p enables you to remove the recursion as well: