2013-06-20 4 views
2

왜 이진 트리에 노드를 삽입하는 동안 우리는 포인터를 사용하는 이유를 알고 싶습니다. 그러나 이진 트리를 탐색하는 동안 트리를 루트 노드에 대한 간단한 포인터로 참조합니다. 하지만 왜 노드를 삽입하는 동안?이진 트리에서 노드를 추가하는 동안 구조체의 포인터에 포인터 사용

포인터가 포인터 인 이유를 이해하는 이유 또는 참조 링크를 제공하는 사람을 도와 줄 수 있습니까?

/*This program clears out all the three methods of traversal */ 

#include<stdio.h> 
#include<stdlib.h> 

/* Let us basically describe how a particular node looks in the binary tree .... Every node in the tree has three major elements , left child, right child, and and the data. */ 

struct TreeNode { 
int data; 
struct TreeNode *leftChild; 
struct TreeNode *rightChild; 
}; 

void inorder(struct TreeNode *bt); 
void preorder(struct TreeNode *bt); 
void postorder(struct TreeNode *bt); 
int insert(struct TreeNode **bt,int num); 

main() 
{ 
int num,elements; 
struct TreeNode *bt; 
int i; 

printf("Enter number of elements to be inserted in the tree"); 
scanf("%d",&num); 

printf("Enter the elements to be inserted inside the tree"); 
for(i=0;i<num;i++) 
{ 
scanf("%d",&elements); 
insert(&bt,elements); 
printf("\n"); 
} 

printf("In Order Traversal \n"); 
inorder(bt); 

printf("Pre Order Traversal \n"); 
preorder(bt); 

printf("Post Order Traversal \n"); 
postorder(bt); 

return 0; 
} 

int insert(struct TreeNode **bt,int num) 
{ 
if(*bt==NULL) 
{ 
*bt= malloc(sizeof(struct TreeNode)); 

(*bt)->leftChild=NULL; 
(*bt)->data=num; 
(*bt)->rightChild=NULL; 

return; 
} 
else{ 
/* */ 
if(num < (*bt)->data) 
{ 
insert(&((*bt)->leftChild),num); 
} 
else 
{ 
insert(&((*bt)->rightChild),num); 
} 
} 
return; 
} 

void inorder(struct TreeNode *bt){ 
if(bt!=NULL){ 


//Process the left node 
inorder(bt->leftChild); 

/*print the data of the parent node */ 
//printf(" %d ", bt->data); 

/*process the right node */ 
inorder(bt->rightChild); 
} 

} 

void preorder(struct TreeNode *bt){ 
if(bt) 
{ 
//Process the parent node first 
printf("%d",bt->data); 

//Process the left node. 
preorder(bt->leftChild); 

//Process the right node. 
preorder(bt->rightChild); 


} 

} 


void postorder(struct TreeNode *bt){ 

if(bt) 
{ 
//process the left child 
postorder(bt->leftChild); 

//process the right child 
postorder(bt->rightChild); 


//process the parent node 
printf("%d",bt->data); 


} 
} 
+0

하셨습니까 ' '* /'여기서 :'/ * 오른쪽 노드를 처리 하시겠습니까? '? – soon

+0

옙. 알았어. 내 vi 편집기가 한 가지 색 이었어. 그걸 알아낼 수는 없었어.하지만 여전히 포인터에 대한 질문 포인터는 아직 풀리지 않았다. –

+0

이제 코드가 실행 중이다 !! 여전히 노드를 삽입하는 동안 그것 포인터 포인터입니다 알아낼 수 없습니다. 아무도 참조를 제공 할 수 있습니다. 또는 이유 –

답변

3

"I want to know the reason why do we use, pointer to pointer while inserting nodes in the binary tree. But, While traversing the binary tree, we just refer the tree by simple pointer to the root node. But why while inserting node?"

우리는 실제로 심지어이 응답하도록 코드가 필요하지 않습니다. 을 C의 외부 함수에서 (수정하려면) 데이터를 수정하려면 데이터 주소가 필요합니다. 마찬가지로 :

main() { 
    int x = 2; 
    change_me(x); 
    printf("%d\n", x); // prints 2 
} 

void change_me(int x){ 
    x++; 
} 

에는 의미가 없습니다. 이 예에서는 로컬 복사본을 가져올 수 있습니다. 값에 대한 변경 사항은 로컬 범위에만 있습니다. 이러한 변경 사항을 호출 함수로 다시 전달하려면 주소가 필요합니다.

main() { 
    int x = 2; 
    change_me(&x); 
    printf("%d\n", x); // prints 3 
} 

void change_me(int* x){ 
    (*x)++; 
} 

포인터에 대해서도 마찬가지입니다. 연결된 목록의 예제에서 값을 인쇄하려면 트리를 가로 질러 데이터를 읽어야합니다. 포인터를 변경하기 위해 아무 것도 변경할 필요가 없습니다. 그러나 나무를 수정하고 싶다면 :

struct node{ 
    int val; 
    sturct node* next; 
}; 

main() { 
    struct node* head = malloc(sizeof(struct node)); 
    head->val = 3; 
    insert_a_node_in_front(head); 
} 

insert_a_node_in_front(node * ptr) { 
    struct node* temp = ptr; 
    ptr = malloc(sizeof(struct node)); 
    ptr->val = 5; 
    ptr->next = temp; 
} 

글쎄, 어떨까요? head의 값이 변경되지 않았기 때문에 실제로 노드를 삽입하지 않았습니다. 여전히 val==3 인 원래 노드를 가리 킵니다. 이유는 이전과 같기 때문에 매개 변수의 로컬 복사본 값을 변경하려고했습니다. 포인터를 사용하는 방법에 대한

insert_a_node_in_front(&head); 
} 

insert_a_node_in_front(node ** ptr) { 
    struct node* temp = (*ptr); 
    (*ptr) = malloc(sizeof(struct node)); 
    (*ptr)->val = 5; 
    (*ptr)->next = temp; 
} 
+0

이것은 명확하게 나를 이해하는 데 도움이되었습니다! 감사 –

2

새로운 구조체 treenode를 malloc하는 첫 번째 부분 때문입니다. 당신은 단지 구조체 TreeNode를 전달하는 경우 *이 다음과 같이 보일 것이다 : 그와

int insert(struct TreeNode *bt,int num) 
{ 
    if(bt==NULL) 
    { 
     bt= malloc(sizeof(struct TreeNode)); 

     (bt)->leftChild=NULL; 
     (bt)->data=num; 
     (bt)->rightChild=NULL; 

    return; 
    } 
    ... 
} 

문제가 될 것이라고 BT 메인에서 BT가 변경 될 것 때문에 삽입하는 지역이다. 따라서 main의 bt에 대한 포인터를 전달하면 insert가 그것을 변경할 수 있습니다.

+0

도움 주셔서 대단히 감사드립니다! –

관련 문제