다음 그림과 같은 구조를 가지는 것이 트리(Tree)라 한다.
트리는 Root, Branch, Leaf 요소를 가진다.
Root(뿌리) : 트리 구조에서 가장 위에 있는 노드 (그림 A노드)
Leaf(잎) : 트리 구조에서 가장 끝에 있는 노드 (그림 E, F, H, K 노드)
Branch(가지) : Root와 Leaf 사이에 위치한 노드 (그림 D, G, I, C, D, J 노드)
#include "Tree.h"
TreeNode* Tree_CreateNode( ElementType NewData )
{
TreeNode* NewNode = (TreeNode*)malloc( sizeof(TreeNode) );
NewNode->LeftChild = NULL;
NewNode->RightSibling = NULL;
NewNode->Data = NewData;
return NewNode;
}
void Tree_DestroyNode( TreeNode* Node )
{
free(Node);
}
void Tree_DestroyTree( TreeNode* Root )
{
if ( Root->RightSibling != NULL )
Tree_DestroyTree( Root->RightSibling );
if ( Root->LeftChild != NULL )
Tree_DestroyTree( Root->LeftChild );
Root->LeftChild = NULL;
Root->RightSibling = NULL;
Tree_DestroyNode( Root );
}
void Tree_AddChildNode( TreeNode* Parent, TreeNode *Child)
{
if ( Parent->LeftChild == NULL )
{
Parent->LeftChild = Child;
}
else
{
TreeNode* TempNode = Parent->LeftChild;
while ( TempNode->RightSibling != NULL )
TempNode = TempNode->RightSibling;
TempNode->RightSibling = Child;
}
}
void Tree_PrintTree( TreeNode* Node, int Depth )
{
int i=0;
for ( i=0; i<Depth; i++ ) //깊이만큼 공백 출력
printf(" ");
printf("%c\n", Node->Data); //노드의 데이터 출력
if ( Node->LeftChild != NULL )
Tree_PrintTree(Node->LeftChild, Depth+1);
if ( Node->RightSibling != NULL )
Tree_PrintTree(Node->RightSibling, Depth);
}
'자료 구조' 카테고리의 다른 글
수식 트리 (Expression Tree) (0) | 2020.09.01 |
---|---|
분리 집합 (Disjoint Set) (0) | 2020.09.01 |
Linked Queue(링크드 큐) (0) | 2012.05.23 |
Queue(큐) : 순환 큐(Circular Queue) (0) | 2012.05.17 |
Stack : 사칙 연산 계산기 (0) | 2012.05.14 |