AVL树中的插入功能不会插入

时间:2014-11-23 01:40:22

标签: c nodes avl-tree

我正在使用字符串作为键的avl树。 print语句表明插入正在发生,但在测试函数中,它报告根的左节点和右节点保持为空。

这是我的avl树代码:

#include "AVLAdt.h"

void printVal(node * toPrint){
    printf("\n node value: %s\n", toPrint->nodeValue);
}

node * search(node * root, char * searchVal){
    if(isExternal(root) == 1) return NULL;
    if(strcmp(searchVal,root->nodeValue)<0){
        return(search(root->leftNode,searchVal));
    }
    else if(strcmp(searchVal,root->nodeValue)==0){
        return(root);
    }
    else {
        return(search(root->rightNode,searchVal));
    }
}



/*initialize a node*/   
node * initNode(char * toAdd){
    node * newNode = malloc(sizeof(node));
    strcpy(newNode->nodeValue, toAdd);
    newNode->leftNode = NULL;
    newNode->rightNode = NULL;
    newNode->height = 1;
    return newNode;
}



/*function to insert a new node into tree and rebalance if necessary*/
node * insert(node * root, char * newValue){


    if(root == NULL){
        printf("\n Inserting %s. \n", newValue);
        return(initNode(newValue));

    }
    else{

        if(strcmp(newValue,root->nodeValue)<0){
            printf("go left");
            insert(root->leftNode, newValue);
        }
        else if(strcmp(newValue,root->nodeValue)>0){
            printf("go to right node of %s", root->nodeValue);
            insert(root->rightNode, newValue);
        }
        else{
            root->count++;
            return (root);
        }
    }

测试程序:

#include "AVLAdt.h"

int main(){


    node * root = NULL;

    char * testString = malloc(sizeof(char)*50);
    strcpy(testString, "aa");

    char * testString1 = malloc(sizeof(char)*50);
    strcpy(testString1, "bb");


    printf("does it try to insert?");

    root = insert(root, testString);
    root = insert(root, testString1);

    printVal(root);

    if(getRight(root) == NULL) printf("right is null");
    else{

        printf("right is");
        printVal(getRight(root));
    }

    if(getLeft(root) == NULL) printf("left is null");
    else{

        printf("left is");
        printVal(getRight(root));
    }



    return(0);
}

代码返回“aa”的左右节点都为空。这是为什么?

1 个答案:

答案 0 :(得分:1)

search()函数中,不确定为什么要这样做

if(isExternal(root) == 1) return NULL;

如果node是外部的,即没有任何叶子,您仍然希望将其nodeValuesearchVal进行比较并返回root以防万一比赛。

initNode()函数中,倒数第二行应为

newNode->count = 1;

而不是

newNode->height = 1;

此外,在我看来,在insert()函数中,initNode()的返回值应该分配给root以存储指向新添加的node的指针在树上,即你应该:

return root = initNode(newValue);

而不是

return(initNode(newValue));

(顺便说一下,你也不必在括号中加上返回值)。

WhozCraig已经指出了递归insert()调用的返回值的问题。