2 xyPzwIM abcABdefgCDEF则输出:
wzyxIPM gfCecbDdAaEBF
#include<iostream> #include<cstdio> #include<cstring> #include<cstdlib> #include<string> #include<stack> #include<algorithm> using namespace std; char post[10010]; struct tree { char ch; tree* lchild; tree* rchild; }; tree* newnode() { tree* u = (tree*) new (tree); u->ch = ‘\0‘; u->lchild = u->rchild = NULL; return u; } void bfs(tree* root) { char out[10010]; tree* que[10010] = {NULL}; int font, rear, k = 0; font = 0, rear = 1; que[font] = root; out[k++] = root->ch; while(font < rear) { tree* tmp; tree* next; tmp = que[font++]; if (tmp->lchild != NULL) { next = tmp->lchild; que[rear++] = next; out[k++] = next->ch; } if (tmp->rchild != NULL) { next = tmp->rchild; que[rear++] = next; out[k++] = next->ch; } } for (int i = k - 1; i >= 0; i--) cout<<out[i]; } int main () { int t, i, n; cin>>t; getchar(); while(t--) { gets(post); n = strlen(post); tree* s[10010]; int k = 0; for (i = 0; i < n; i++) { if (post[i] <= ‘Z‘) //碰到操作符,从栈中取出两个地址,分别作为左右孩子,然后将其根地址再次入栈 { tree* u = newnode(); u->ch = post[i]; u->rchild = s[--k]; u->lchild = s[--k]; s[k++] = u; } else //碰到操作数,将地址其入栈 { tree* u = newnode(); u->ch = post[i]; s[k++] = u; } } tree* root = s[--k]; //把树的根节点取出 bfs(root); //进行层次遍历 puts(""); memset(post, 0, sizeof(post)); } return 0; }
[UVA 11234] Expressions (二叉树的建立与层次遍历)
原文:http://blog.csdn.net/sio__five/article/details/18420401