본문 바로가기

프로그래밍/자료구조

연결리트스 이진트리

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



typedef char element;

//이진트리 데이터 구조
typedef struct treenode{   
   element data;
   struct treenode* left;
   struct treenode* right;
}TreeNode;

typedef struct{
   TreeNode* root;
}BT;

//이진트리 연산 구조
BT* createBT(){
   BT *bt = (BT*)malloc(sizeof(BT));
   bt->root = NULL;
   return  bt;
}

int isEmpty(BT* bt){
   if(bt->root = NULL) return 1;
   return 0;
}

TreeNode* makeBT(element data, TreeNode* left, TreeNode* right){
   TreeNode *newNode = (TreeNode*)malloc(sizeof(TreeNode));
   if(newNode == NULL){         //예외 처리
      printf("OverFlow! \n");
      return NULL;
   }

   newNode->data = data;
   newNode->left = left;
   newNode->right = right;

   return newNode;
}

TreeNode* leftSubtree(TreeNode* root){
   return root->left;
}

TreeNode* rightSubtree(TreeNode* root){
   return root->right;
}

element getData(TreeNode* current){
   return current->data;
}

void preorder(TreeNode * root) {//전위순회
	if (root == NULL) return;
	printf("%c\t", root->data);
	preorder(root->left);
	preorder(root->right);
}

void inorder(TreeNode * root) {//중위순회
	if (root == NULL) return;
	inorder(root->left);
	printf("%c\t", root->data);
	inorder(root->right);
}

void postorder(TreeNode * root) { //후위순회
	if (root == NULL) return;
	postorder(root->left);
	postorder(root->right);
	printf("%c\t", root->data);
}

int main(){
   BT *bt1, *bt2;
   TreeNode *n01, *n02, *n03, *n04, *n05, *n06, *n07, *n08, *n09, *n10, *n11, *n12; 
   TreeNode *current;

   bt1 = createBT();
   bt2 = createBT();

   n08 = makeBT('H', NULL, NULL);
   n09 = makeBT('I', NULL, NULL);
   n10 = makeBT('J', NULL, NULL);
   n11 = makeBT('K', NULL, NULL);
   n12 = makeBT('L', NULL, NULL);

   n04 = makeBT('D', n08, n09);
   n05 = makeBT('E', n10, n11);
   n06 = makeBT('F', n12, NULL);
   n07 = makeBT('G', NULL, NULL);
   
   n02 = makeBT('B', n04, n05);
   n03 = makeBT('C', n06, n07);
   
   n01 = makeBT('A', n02, n03);

   bt1->root = n01;

   bt2->root = leftSubtree(bt1->root);

   current = bt1->root;
   while(current !=NULL){
      printf("%c \n", getData(current));
      current = leftSubtree(current);
   }
   printf("\n");

   preorder(bt1->root);
   printf("\n");
   inorder(bt1->root);
   printf("\n");
   postorder(bt1->root);
   return 0;
}

'프로그래밍 > 자료구조' 카테고리의 다른 글

연결리스트 이진 탐색 트리  (0) 2019.11.14
연결리스트  (0) 2019.11.04
배열 순차리스트  (0) 2019.11.04
연결리스트 큐(Queue) 구현  (0) 2019.10.18
배열을 이용한 큐(Queue)  (0) 2019.10.17