-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path이진검색트리.cpp
62 lines (60 loc) · 1.12 KB
/
이진검색트리.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <stdio.h>
#include <stdlib.h>
typedef struct tree_node *tree_ptr;
struct tree_node{
int data;
tree_ptr left;
tree_ptr right;
};
void insert_BST(tree_ptr tree,int item);
void postorder(tree_ptr ptr);
int main(){
tree_ptr tree = (tree_ptr)malloc(sizeof(struct tree_node));
int n;
scanf("%d\n", &n);
tree->data = n;
tree->left = NULL;
tree->right = NULL;
while(scanf("%d\n", &n)!=EOF){
insert_BST(tree, n);
}
postorder(tree);
}
void insert_BST(tree_ptr tree,int item){
tree_ptr node = (tree_ptr)malloc(sizeof(struct tree_node));
tree_ptr temp, prev;
node->data = item;
node->left = NULL;
node->right = NULL;
if(tree == NULL) tree = node;
else{
temp = tree;
prev = NULL;
while(1){
prev = temp;
if(item < prev->data){
temp = temp->left;
if(temp == NULL){
prev->left = node;
return;
}
}
else if(item > prev->data){
temp = temp->right;
if(temp==NULL){
prev->right = node;
return;
}
}
else return;
}
}
}
void postorder(tree_ptr ptr){
if(ptr){
postorder(ptr->left);
postorder(ptr->right);
printf("%d\n", ptr->data);
}
else return;
}