트리 연결리스트로 구현하기
2019. 10. 12. 23:14ㆍ알고리즘/암기
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
typedef struct node Node; | |
struct node { | |
int data; | |
Node* leftChild; | |
Node* rightChild; | |
}; | |
Node* initNode(int data, Node* left, Node* right) { | |
Node* node = (Node*)malloc(sizeof(Node)); | |
if (node != NULL) { | |
node->data = data; | |
node->leftChild = left; | |
node->rightChild = right; | |
} | |
return node; | |
} | |
void preorder(Node* root) { | |
if (root != NULL) { | |
printf("%d ", root->data); | |
preorder(root->leftChild); | |
preorder(root->rightChild); | |
} | |
} | |
void inorder(Node* root) { | |
if (root != NULL) { | |
inorder(root->leftChild); | |
printf("%d ", root->data); | |
inorder(root->rightChild); | |
} | |
} | |
void postorder(Node* root) { | |
if (root != NULL) { | |
postorder(root->leftChild); | |
postorder(root->rightChild); | |
printf("%d ", root->data); | |
} | |
} | |
int main(void) { | |
Node* n7 = initNode(50, NULL, NULL); | |
Node* n6 = initNode(37, NULL, NULL); | |
Node* n5 = initNode(23, NULL, NULL); | |
Node* n4 = initNode(5, NULL, NULL); | |
Node* n3 = initNode(48, n6, n7); | |
Node* n2 = initNode(17, n4, n5); | |
Node* n1 = initNode(30, n2, n3); | |
preorder(n1); | |
printf("\n"); | |
inorder(n1); | |
printf("\n"); | |
postorder(n1); | |
printf("\n"); | |
return 0; | |
} |
'알고리즘 > 암기' 카테고리의 다른 글
힙 정렬 (0) | 2019.10.14 |
---|---|
Stack 2개로 Queue 구현하기 [C++] (0) | 2019.10.13 |
우선순위 큐 삽입, 삭제 C로 구현하기 (0) | 2019.10.12 |
기수 정렬 Radix sort (0) | 2019.10.12 |
우선순위 큐 정렬 - 2 (0) | 2019.10.10 |