/*
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(SBTNode* Node);
void SBT_DestroyNode(SBTNode* Root);
void SBT_PreorderPrintTree(SBTNode* Node);
void SBT_InorderPrintTree(SBTNode* Node);
void SBT_PostorderPrintTree(SBTNode* Node);
#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(SBTNode* Node) {
free(Node);
}
void SBT_DestroyTree(SBTNode* Root) {
if (Root == NULL) return;
SBT_DestroyTree(Root->Left);
SBT_DestroyTree(Root->Right);
SBT_DestroyNode(Root);
}
void SBT_PreorderPrintTree(SBTNode* Node) {
if (Node == NULL) return;
//노드를 출력
//노드를 출력
printf("%c", Node->data);
//왼쪽 하위 트리 출력
SBT_PreorderPrintTree(Node->Left);
//오른쪽 하위 트리 출력
SBT_PreorderPrintTree(Node->Right);
}
void SBT_InorderPrintTree(SBTNode* Node) {
if (Node == NULL) return;
//왼쪽 하위 트리 출력
SBT_InorderPrintTree(Node->Left);
//노드를 출력
//노드를 출력
printf("%c", Node->data);
//오른쪽 하위 트리 출력
SBT_InorderPrintTree(Node->Right);
//오른쪽 하위 트리 출력
SBT_InorderPrintTree(Node->Right);
}
void SBT_PostorderPrintTree(SBTNode* Node) {
if (Node == NULL) return;
//왼쪽 하위 트리 출력
//왼쪽 하위 트리 출력
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");
}
댓글 없음:
댓글 쓰기