/* 트리의 노드 전부 삭제 후, 루트 삭제. */
void FreeTree(Node* rootNode) {
if (NULL != rootNode->leftChild) {
FreeTree(rootNode->leftChild);
}
if (NULL != rootNode->rightSibling) {
FreeTree(rootNode->rightSibling);
}
rootNode->leftChild = NULL;
rootNode->rightSibling = NULL;
FreeNode(rootNode);
}
자식 노드 연결
부모 노드와 자식 노드 포인터를 매개변수로 입력 받습니다.
자식이 없다면, 자식에 할당해줍니다.
자식이 있다면, rightSibling 포인터를 이용하여 마지막 자식을 찾아내서 새 자식(?)을 연결합니다.
/* 부모에게 자식 연결 */
void ConnectChild(Node** parent, Node* child) {
if (NULL == (*parent)->leftChild) { // 자식이 없다면,
(*parent)->leftChild = child;
}
else {// 자식이 있다면, 끝을 찾아서 연결한다.
Node* lastChild = (*parent)->leftChild;
while (NULL != lastChild->rightSibling) {
lastChild = lastChild->rightSibling;
}
lastChild->rightSibling = child;
}
}
트리를 순회하며 출력
자식과 형제를 출력하기 위해 함수를 재귀 호출 합니다.
/* 트리 순회하며 출력 */
void Print(Node* node, int depth) {
int num = 0;
// 깊이 만큼 들여쓰기
for (num = 0; num < depth; num++) {
printf(" ");
}
// 데이터 출력
printf("%d\n", node->data);
// depth를 더해서 자식노드를 출력하도록 함수 재귀 호출
if (NULL != node->leftChild) {
Print(node->leftChild, depth++);
}
// 형제노드를 출력하도록 함수 재귀 호출 (depth 유지.)
if (NULL != node->rightSibling) {
Print(node->rightSibling, depth);
}
}