0
문자열을 키로 사용하여 avl 트리를 작업하고 있습니다. print 문은 삽입이 일어나고 있음을 나타내지 만 테스트 기능에서는 루트의 왼쪽과 오른쪽 노드가 null로 남아 있다고보고합니다.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);
}
}
테스트 프로그램 :
여기 내 AVL 트리 코드
#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"모두 왼쪽과 오른쪽 노드가 null 있음을 반환합니다. 왜 이런거야? 하지 있는지 node
이 외부 경우
if(isExternal(root) == 1) return NULL;
할 이유, 즉 어떤 잎이없는 search()
기능에
'insert' 함수의 반환 값에 세심한주의를 기울이십시오. 'insert (root-> leftNode, newValue)'와'insert (root-> rightNode, newValue);를 호출 할 때 이것이 중요하다고 생각하십니까? 둘 다 현재 결과를 무시합니까? – WhozCraig
정확하게 나에게 대답을주지 않고보고있는 곳을 말해 줘서 고마워, 아직도 나에게 하하했다. 재귀 함수를 중심으로 머리를 감싸는 데 여전히 어려움을 겪고 있습니다. – tke
걱정할 필요가 없습니다. 재귀는 처음에 올 때 변덕스러운 것입니다. 호출 스택 및/또는 반환 값은 대개 내림차순 중에 상황이 "저장되는"위치이므로 나중에 나중에 복구 할 수 있습니다. 행운을 빌어 요. – WhozCraig