문제
다음과 같은 구현에 어떤 문제가 있습니다 이진 검색 트리 (BST)? 나는 포인터에 포인터를 사용하는 것이 낫다고 들었습니다. struct
삽입 함수의 인수로서 노드.
struct node
{
int key_value;
struct node* left;
struct node* right;
};
insert(int key, struct node *leaf)
{
if( leaf == 0 )
{
leaf = (struct node*) malloc( sizeof( struct node ) );
leaf->key_value = key;
/* initialize the children to null */
leaf->left = 0;
leaf->right = 0;
}
else if(key < leaf->key_value)
{
insert( key, leaf->left );
}
else if(key > leaf->key_value)
{
insert( key, leaf->right );
}
}
해결책
이 라인 :
leaf = (struct node*) malloc( sizeof( struct node ) );
새로운 가치를 제공합니다 leaf
, 새로 할당 된 메모리를 가리키십시오. 그러나 새로운 값은 함수를 남기지 않습니다. 함수가 돌아 오면 발신자는 여전히 기존을 참조합니다. leaf
, 그리고 메모리 누출이있을 것입니다.
수정하기 위해 취할 수있는 두 가지 접근 방식이 있습니다.
1. 포인터를 사용하여 포인터를 사용하십시오
void insert(int key, struct node **leaf)
{
if(*leaf == 0 )
{
*leaf = (struct node*) malloc( sizeof( struct node ) );
...
}
/* In caller -- & is prepended to current_leaf. */
insert(37, ¤t_leaf);
2. 새 잎 (또는 변화가없는 경우 오래된 잎)을 반환하십시오.
struct node *insert(int key, struct node *leaf)
{
if(leaf == 0 )
{
leaf = (struct node*) malloc( sizeof( struct node ) );
...
}
return leaf;
}
/* In caller -- & is prepended to current_leaf. */
current_leaf = insert(37, current_leaf);
포인터에 대한 포인터는 이해하기 어려운 임계 값에 가깝습니다. 아마 두 번째 옵션으로 갈 것입니다. insert
현재 다른 것을 반환하지 않습니다.
다른 팁
노드가 삽입되면 (Leaf == 0), 부모를 변경하지 않았으므로 새 노드는 고아가됩니다.
다시 말해, 트리는 삽입으로 얼마나 많은 노드가 호출되었는지에 관계없이 여전히 하나의 노드처럼 보입니다.
#include<stdio.h>
typedef struct tnode{
int data;
struct tnode *left,*right;
}TNODE;
TNODE * createTNode(int key){
TNODE *nnode;
nnode=(TNODE *)malloc(sizeof(TNODE));
nnode->data=key;
nnode->left=NULL;
nnode->right=NULL;
return nnode;
}
TNODE * insertBST(TNODE *root,int key){
TNODE *nnode,*parent,*temp;
temp=root;
while(temp){
parent=temp;
if(temp->data > key)
temp=temp->left;
else
temp=temp->right;
}
nnode=createTNode(key);
if(root==NULL)
root=nnode;
else if(parent->data>key)
parent->left=nnode;
else
parent->right=nnode;
return root;
}
void preorder(TNODE *root){
if(root){
printf("%5d",root->data);
preorder(root->left);
preorder(root->right);
}
}
void inorder(TNODE *root){
if(root){
inorder(root->left);
printf("%5d",root->data);
inorder(root->right);
}
}
void postorder(TNODE *root){
if(root){
postorder(root->left);
postorder(root->right);
printf("%5d",root->data);
}
}
main(){
TNODE *root=NULL;
int ch,key;
do{
printf("\n\n1-Insert\t2-Preorder\n3-Inorder\t4-Postorder\n5-Exit\n");
printf("Enter Your Choice: ");
scanf("%d",&ch);
switch(ch){
case 1:
printf("Enter Element: ");
scanf("%d",&key);
root=insertBST(root,key);
break;
case 2:
preorder(root);
break;
case 3:
inorder(root);
break;
case 4:
postorder(root);
break;
default:
printf("\nWrong Choice!!");
}
}while(ch!=5);
getch();
return 0;
}
제휴하지 않습니다 StackOverflow