原題鏈接:http://ac.jobdu.com/problem.php?pid=1184
簡單的二叉樹重建,遍歷.
如下:
1 #include<cstdio> 2 #include<cstdlib> 3 #include<cstring> 4 #include<vector> 5 struct node{ 6 char key; 7 node *ch[2]; 8 node(char d) : key(d) { ch[0] = ch[1] = NULL; } 9 }*root = NULL; 10 int n = 0; 11 static int k = -1; 12 char buf[110]; 13 void built(node *&p){ 14 k++; 15 if (k > n) return; 16 if (buf[k] != '#'){ 17 p = new node(buf[k]); 18 built(p->ch[0]); 19 built(p->ch[1]); 20 } 21 } 22 void travle(node *x){ 23 if (x != NULL){ 24 travle(x->ch[0]); 25 printf("%c ", x->key); 26 travle(x->ch[1]); 27 } 28 } 29 void _free(node *x){ 30 if (x != NULL){ 31 _free(x->ch[0]); 32 _free(x->ch[1]); 33 delete x; 34 } 35 } 36 int main(){ 37 #ifdef LOCAL 38 freopen("in.txt", "r", stdin); 39 freopen("out.txt", "w+", stdout); 40 #endif 41 while (~scanf("%s", buf)){ 42 k = -1, root = NULL, n = strlen(buf); 43 built(root); 44 travle(root); 45 _free(root); 46 printf("\n"); 47 } 48 return 0; 49 } View Code