본문 바로가기
Programming/C, C++

트리생성

by 붕어고기 2013. 5. 21.
반응형

//종료가 -1 이므로 그부분 수정

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

struct node {
 int data;
 struct node *PL;
 struct node *PR;
}*root,*p,*temp,*del;

void preorder(struct node * root) {
 if(root) {
  printf("%d ",root->data);
  preorder(root->PL);
  preorder(root->PR);
 }
}

void inorder(struct node * root) {
 if(root) {
  inorder(root->PL);
  printf("%d ",root->data);
  inorder(root->PR);
 }
}

void postorder(struct node * root) {
 if(root) {
  postorder(root->PL);
  postorder(root->PR);
  printf("%d ",root->data);
 }
}


int main(void) {
 int i;

 printf("root 숫자를 입력 하시오 : ");
 scanf("%d",&i);

 p=(struct node *)malloc(sizeof(struct node));
 p->data=i;
 p->PL=NULL;
 p->PR=NULL;

 root=temp=p;

 while(1) {
  printf("숫자를 입력 하시오(정지: -1) : ");
  scanf("%d",&i);

  if(i==-1)
   break;
  else{
   while(1) {
    if(i<temp->data && temp->PL==NULL) {
     p=(struct node *)malloc(sizeof(struct node));
     p->data=i;
     p->PL=NULL;
     p->PR=NULL;
     temp->PL=p;
     break;
    }

    if(i>temp->data && temp->PR==NULL) {
     p=(struct node *)malloc(sizeof(struct node));
     p->data=i;
     p->PL=NULL;
     p->PR=NULL;
     temp->PR=p;
     break;
    }

    else{
     if(i<temp->data)
      temp=temp->PL;
     else
      temp=temp->PR;
    }
   }
  }

  temp=root;
 }
 printf("preorder : ");
 preorder(root);
 printf("\ninorder : ");
 inorder(root);
 printf("\npostorder : ");
 postorder(root);

 printf("\n삭제할 숫자를 입력 하시오 : ");
 scanf("%d",&i);

 del=root;
 while(1) {
  if(del->data == i) {
   temp->PR=del->PR;
   free(del);
   break;
  }
  if(i < del->data) {
   temp=del;
   del=del->PL;
  }else{
   temp=del;
   del=del->PR;
  }
 }

 printf("preorder : ");
 preorder(root);
 printf("\ninorder : ");
 inorder(root);
 printf("\npostorder : ");
 postorder(root);

 return 0;
}

반응형

'Programming > C, C++' 카테고리의 다른 글

수식트리  (0) 2013.05.21
Doublelinkedlist  (0) 2012.12.26
Linkedlist  (0) 2012.12.26
Circular Queue  (0) 2012.12.21
Stack  (0) 2012.12.20

댓글