반응형
SMALL
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 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 | #include <stdio.h> #include <stdlib.h> struct node { int data; struct node *left; struct node *right; }; struct node *root = 0; // returns 1 if _data is found // returns 0 otherwise. int searchBST(int _data) { struct node *temp = root; while (temp != 0) { if (temp->data == _data) { return 1; } else { if (_data < temp->data) { temp = temp->left; } else { temp = temp->right; } } } return 0; } void addToBST(int _data) { struct node *cur = 0; cur = (struct node *)malloc(sizeof(struct node)); cur->data = _data; cur->left = cur->right = 0; if (root == 0) { root = cur; return; } else { struct node *temp = root; while (1) { if (cur->data < temp->data) // left { if (temp->left == 0) { temp->left = cur; return; } else { temp = temp->left; } } else // right { if (temp->right == 0) { temp->right = cur; return; } else { temp = temp->right; } } } } } void traversal(struct node *me) { if (me != 0) { traversal(me->left); printf("%d ", me->data); traversal(me->right); } } int main(void) { addToBST(5); addToBST(3); addToBST(7); addToBST(1); addToBST(4); addToBST(6); addToBST(10); traversal(root); return 0; } |
반응형
LIST
'데이터구조 > 소스코드' 카테고리의 다른 글
Quick sort 소스코드 (0) | 2016.05.26 |
---|---|
Priority Queue, Min Heap (0) | 2016.05.16 |
OJ 1161 (0) | 2016.04.25 |
OJ 1160 (0) | 2016.04.25 |
OJ 1165 (0) | 2016.04.25 |