트리 // 재귀함수
# include <stdio.h>
# include <stdlib.h>
# define _AND_ &&
# define _ERROR_ 1
typedef struct _Node {
int data;
struct _Node* left_n;
struct _Node* right_n;
}Node;
Node* root = NULL;
// ++++++++++++++++++++++++++++++++++++++++
void initTree(int paramNum);
Node* AddChildNode(Node* pNode, int data);
void PreOrder(Node *Proot);
// ++++++++++++++++++++++++++++++++++++++++
int main(void) {
initTree(1); // 최상위 노드
Node* Leftnode = NULL;
Node* Rightnode = NULL;
Leftnode = AddChildNode(root, 2);
Rightnode = AddChildNode(root, 3);
AddChildNode(Leftnode, 4);
PreOrder(root);
printf("\n");
return 0;
} // end of main function
void initTree(int paramNum) {
Node* retNode = NULL;
retNode = (Node*)malloc(sizeof(Node));
if (retNode == NULL) {
exit(_ERROR_);
}
else {
//retNode != NULL
retNode->data = paramNum;
retNode->left_n = NULL;
retNode->right_n = NULL;
root = retNode;
}
} // end of initTree function
Node* AddChildNode(Node* pNode, int data) {
if (pNode->left_n != NULL _AND_ pNode->right_n != NULL) {
printf("child node full ... !!!\n");
exit(_ERROR_);
}
else {
//pNode->left_n == NULL OR pNode->right_n == NULL
if (pNode->left_n == NULL) {
// LEFT CHILD
Node* L_Child = (Node*)malloc(sizeof(Node));
if (L_Child == NULL) {
printf("left_child malloc error ... !!!\n");
exit(_ERROR_);
}
else { // L_Child != NULL
L_Child->left_n = NULL;
L_Child->right_n = NULL;
L_Child->data = data;
pNode->left_n = L_Child;
return L_Child;
}
}
else {
// pNode->left_n != NULL
// RIGHT CHILD
Node* R_Child = (Node*)malloc(sizeof(Node));
if (R_Child == NULL) {
printf("right_child malloc error ... !!!\n");
exit(_ERROR_);
}
else { // R_Child != NULL
R_Child->left_n = NULL;
R_Child->right_n = NULL;
R_Child->data = data;
pNode->right_n = R_Child;
return R_Child;
}
}
}
} // end of AddChildNode function
void PreOrder(Node *Proot) {
printf("%d [%#x] ", Proot->data, Proot);
if (Proot->left_n) { PreOrder(Proot->left_n); }
if (Proot->right_n) { PreOrder(Proot->right_n); }
} // end of PreOrder function