簡體   English   中英

插入功能到AVL樹中不會插入

[英]Insertion function into AVL tree won't insert

我正在使用字符串作為鍵的avl樹上工作。 打印語句表明正在進行插入,但是在測試功能中它報告根的左節點和右節點保持為空。

這是我的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”的左右節點均為空。 為什么是這樣?

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()調用的返回值問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM