알고리즘
쿼드 트리
millycoder
2017. 1. 1. 23:37
쿼드 트리 뒤집기
트리 만들기만 하면 된다!!
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 | // 쿼드 트리 #include <iostream> using namespace std; int C; char OrigStr[1001]; int index = 0; //인덱스를 글로벌로 설정해서 꼬이지 않게 함. typedef struct tree* Quadtree; struct tree { char elem; Quadtree child[4]; }; void printTree(Quadtree t) { if (t == NULL) { return; } cout << t->elem; for (int i = 0; i < 4; i++) { printTree(t->child[i]); } } Quadtree reverseTree(Quadtree t) { if (t == NULL) return NULL; if (t->elem != 'x') return t; for (int i = 0; i < 2; i++) { Quadtree tmp = NULL; tmp = t->child[i]; t->child[i] = t->child[i + 2]; t->child[i + 2] = tmp; } for (int i = 0; i < 4; i++) { t->child[i] = reverseTree(t->child[i]); } return t; } Quadtree createTree(Quadtree t) { char current = OrigStr[index]; // base condition if (current == '\0') return t; if (t != NULL) return t; // null ptr 메모리할당 t = (Quadtree)malloc(sizeof(tree)); t->elem = current; index++; //NULL로 초기화 함 for (int i = 0; i < 4; ++i) { t->child[i] = NULL; } if (current == 'x') { for (int i = 0; i < 4; ++i) { t->child[i] = createTree(t->child[i]); } } return t; } int main() { //freopen("input.txt", "r", stdin); cin >> C; for (int c = 0; c < C; ++c) { cin >> OrigStr; Quadtree t = NULL; index = 0; t = createTree(t); //printTree(t); //cout << endl; t = reverseTree(t); printTree(t); cout << endl; } return 0; } | cs |