Skip to content

Commit

Permalink
Merge pull request #45 from AlgoLeadMe/14-pu2rile
Browse files Browse the repository at this point in the history
14-pu2rile
  • Loading branch information
pu2rile authored Sep 4, 2024
2 parents 12d0a07 + c7a7bae commit 6663b60
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 0 deletions.
Binary file modified .DS_Store
Binary file not shown.
Binary file added pu2rile/ํŠธ๋ฆฌ/.DS_Store
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

typedef struct TreeNode {
int data;
struct TreeNode *left, *right;
} TreeNode;

// ์ƒˆ๋กœ์šด ๋…ธ๋“œ๋ฅผ ์ƒ์„ฑํ•˜๋Š” ํ•จ์ˆ˜
TreeNode* new_node(int key) {
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
node->data = key;
node->left = node->right = NULL;
return node;
}

// ์ „์œ„ ์ˆœํšŒ ๋ฐฐ์—ด์„ ์ด์šฉํ•ด BST๋ฅผ ์ƒ์„ฑํ•˜๋Š” ํ•จ์ˆ˜
TreeNode* construct_bst(int pre[], int* preIndex, int key, int min, int max, int size) {
// ํŠธ๋ฆฌ๊ฐ€ ๊ณต๋ฐฑ์ด๋ฉด NULL ๋ฐ˜ํ™˜
if (*preIndex >= size)
return NULL;

TreeNode* root = NULL;

// ํ˜„์žฌ key๊ฐ€ min๊ณผ max ์‚ฌ์ด์— ์žˆ์„ ๋•Œ๋งŒ ๋…ธ๋“œ๋ฅผ ์ƒ์„ฑ
if (key > min && key < max) {
root = new_node(key);
*preIndex = *preIndex + 1;

if (*preIndex < size) {
// ์™ผ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ๋ฅผ ๊ตฌ์„ฑ
root->left = construct_bst(pre, preIndex, pre[*preIndex], min, key, size);
}
if (*preIndex < size) {
// ์˜ค๋ฅธ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ๋ฅผ ๊ตฌ์„ฑ
root->right = construct_bst(pre, preIndex, pre[*preIndex], key, max, size);
}
}
return root;
}

// ํ›„์œ„ ์ˆœํšŒ ํ•จ์ˆ˜
void post_order(TreeNode* root) {
if (root) {
post_order(root->left); // ์™ผ์ชฝ ์„œ๋ธŒ ํŠธ๋ฆฌ ์ˆœํšŒ
post_order(root->right); // ์˜ค๋ฅธ์ชฝ ์„œ๋ธŒ ํŠธ๋ฆฌ ์ˆœํšŒ
printf("%d\n", root->data); // ๋…ธ๋“œ ๋ฐฉ๋ฌธ
}
}

int main(void) {
int pre[10000]; // ์ตœ๋Œ€ 10000๊ฐœ์˜ ๋…ธ๋“œ๋ฅผ ์ž…๋ ฅ๋ฐ›์„ ์ˆ˜ ์žˆ๋„๋ก ๋ฐฐ์—ด ํฌ๊ธฐ๋ฅผ ์ง€์ •
int key;
int size = 0;

while (scanf("%d", &key) != EOF) {
pre[size++] = key;
}

int preIndex = 0;
if (size > 0) {
TreeNode* root = construct_bst(pre, &preIndex, pre[0], INT_MIN, INT_MAX, size);
post_order(root);
}

return 0;
}

0 comments on commit 6663b60

Please sign in to comment.