이진 트리
모든 노드가 최대 2개의 자식을 가질 수 있는 트리이다.
컴파일러나 검색 등에 사용되는 특수 자료구조 (ex : 이진 탐색 트리(Binary Search Tree), 수식 이진 트리(Expression Binary Tree))
이진 트리의 형태
포화 이진 트리 (Full Binary Tree): 잎 노드를 제외한 모든 노드들이 2개의 자식을 가지고 있는 트리
완전 이진 트리 (Complete Binary Tree): 잎 노드들이 트리의 왼쪽부터 채워진 트리
아래의 그림은 완전 이진 트리가 아닌 예이다.
높이 균형 트리 (Height Balanced Tree)
루트 노드를 기준으로 왼쪽 하위 트리와 오른쪽 하위 트리의 높이가 1이상 차이가 나지 않는 이진 트리
완전 높이 균형 트리 (Completely Height Balanced Tree)
루트 노드를 기준으로 왼쪽 하위 트리와 오른쪽 하위 트리의 높이가 같은 이진 트리
이진 트리의 순회(Traversal)
트리 내의 노드들 사이를 돌아다니는 것을 말한다.
순회의 종류
전위 순회(Preorder) : 루트 노드부터 잎 노드 까지 아래 방향으로 방문하는 방법
중위 순회(Inorder) : 왼쪽 하위 트리부터 오른쪽 하위 트리 방향으로 방문하는 방법
후위 순회(Postorder) : 루트, 왼쪽 하위 트리, 오른쪽 하위 트리 순으로 방문하는 방법
이진 트리 노드 구조체
typedef char ElementType;
typedef struct tagSBTNode
{
struct tagSBTNode* Left;
struct tagSBTNode* Right;
ElementType Data;
} SBTNode;
이진 트리 노드 소스코드
#include "BinaryTree.h"
SBTNode* SBT_CreateNode( ElementType NewData )
{
SBTNode* NewNode = (SBTNode*)malloc( sizeof(SBTNode) );
NewNode->Left = NULL;
NewNode->Right = NULL;
NewNode->Data = NewData;
return NewNode;
}
void SBT_DestroyNode( SBTNode* Node )
{
free(Node);
}
void SBT_DestroyTree( SBTNode* Node )
{
if ( Node == NULL )
return;
/* 왼쪽 하위 트리 소멸 */
SBT_DestroyTree( Node->Left );
/* 오른쪽 하위 트리 소멸 */
SBT_DestroyTree( Node->Right );
/* 루트 노드 소멸 */
SBT_DestroyNode( Node );
}
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 );
}
void SBT_PostorderPrintTree( SBTNode* Node ) //후위 순회를 이용한 이진 트리 출력
{
if ( Node == NULL )
return;
/* 왼쪽 하위 트리 출력 */
SBT_PostorderPrintTree( Node->Left );
/* 오른쪽 하위 트리 출력 */
SBT_PostorderPrintTree( Node->Right );
/* 루트 노드 출력 */
printf( " %c", Node->Data );
}
'자료 구조' 카테고리의 다른 글
수식 트리 (Expression Tree) (0) | 2020.09.01 |
---|---|
분리 집합 (Disjoint Set) (0) | 2020.09.01 |
Tree (트리) (0) | 2012.05.23 |
Linked Queue(링크드 큐) (0) | 2012.05.23 |
Queue(큐) : 순환 큐(Circular Queue) (0) | 2012.05.17 |