7.17.2017

자료구조 BinaryTree

//BinaryTree.h 헤더파일을 만든다.
/*
a
  b e
c  d  f g

전위 : abcdefg
중위 : cbdafeg
후위 : cdbfgea
*/

#ifndef BINART_TREE_H
#define DINART_TREE_H

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

typedef char ElementType;

typedef struct tagSBTNode {
  struct tagSBTNode * Left;
  struct tagSBTNode * Right;

  ElementType data;
}SBTNode;

SBTNode* SBT_CreateNode(ElementType NewData);
void SBT_DestroyNode(SBTNodeNode);
void SBT_DestroyNode(SBTNodeRoot);

void SBT_PreorderPrintTree(SBTNodeNode);
void SBT_InorderPrintTree(SBTNodeNode);
void SBT_PostorderPrintTree(SBTNodeNode);

#endif

============================================================================

#include "BinaryTree.h"

SBTNode* SBT_CreateNode(ElementType NewData) {
  SBTNode* NewNode = (SBTNode*)malloc(sizeof(SBTNode));
  NewNode->Left = NULL;
  NewNode->Right = NULL;
  NewNode->data = NewData;
  return NewData;
}

void SBT_DestroyNode(SBTNodeNode) {
  free(Node);

}

void SBT_DestroyTree(SBTNodeRoot) {
  if (Root == NULL) return;
  SBT_DestroyTree(Root->Left);
  SBT_DestroyTree(Root->Right);
  SBT_DestroyNode(Root);
}

void SBT_PreorderPrintTree(SBTNodeNode) {
  if (Node == NULLreturn;
  //노드를 출력
  printf("%c"Node->data);
  //왼쪽 하위 트리 출력
  SBT_PreorderPrintTree(Node->Left);
  //오른쪽 하위 트리 출력
  SBT_PreorderPrintTree(Node->Right);
}

void SBT_InorderPrintTree(SBTNodeNode) {
  if (Node == NULLreturn;
  //왼쪽 하위 트리 출력
  SBT_InorderPrintTree(Node->Left);
  //노드를 출력
  printf("%c"Node->data);
  //오른쪽 하위 트리 출력
  SBT_InorderPrintTree(Node->Right);
}

void SBT_PostorderPrintTree(SBTNode* Node) {
  if (Node == NULLreturn;
  //왼쪽 하위 트리 출력
  SBT_PostorderPrintTree(Node->Left);
  //오른쪽 하위 트리 출력
  SBT_PostorderPrintTree(Node->Right);
  //노드를 출력
  printf("%c"Node->data);
}

void main() {
  //노드 생성하기
  SBTNode* A = SBT_CreateNode('A');
  SBTNode* B = SBT_CreateNode('B');
  SBTNode* C = SBT_CreateNode('C');
  SBTNode* D = SBT_CreateNode('D');
  SBTNode* E = SBT_CreateNode('E');
  SBTNode* F = SBT_CreateNode('F');
  SBTNode* G = SBT_CreateNode('G');

  //트리에 노드 추가
  A->Left = B;
  B->Left = C;
  B->Right = D;

  A->Right = E;
  E->Left = F;
  E->Right = G;

  //트리 출력
  printf("Preorder...\n");
  SBT_PreorderPrintTree(A);
  printf("\n\n");

  printf("Inorder...\n");
  SBT_PreorderPrintTree(A);
  printf("\n\n");

  printf("Postorder...\n");
  SBT_PreorderPrintTree(A);
  printf("\n\n");

  //트리 소멸시키기
SBT_DestroyTree(Data);

  system("pause");
}

댓글 없음:

댓글 쓰기