UVa 11234 - Expressions

来源:互联网 发布:标准型矩阵是什么 编辑:程序博客网 时间:2024/06/16 22:50

题目:给你一个后缀表达式,展开成二叉树,然后从深层向根的方向输出树上的字符。

分析:DS,递归,搜索。利用递归建树,然后bfs,逆序输出即可。

说明:目标550题!

#include <algorithm>#include <iostream>#include <cstdlib>#include <cstring>#include <cstdio>#include <cmath>using namespace std;char Str[10001];typedef struct tnode{char   V;tnode *L;tnode *R;}tnode;tnode Node[10001];int   TreeSize,Now;tnode* madetree(){int id = TreeSize ++;Node[id].V = Str[-- Now];if (Node[id].V <= 'Z') {Node[id].R = madetree();Node[id].L = madetree();}return &Node[id];}tnode* Q[10001];char output[10001];void bfs(tnode *root){int move = 0,save = 0,count = 0;Q[save ++] = root;while (move < save) {tnode* now = Q[move ++];output[count ++] = now->V;if (now->L) Q[save ++] = now->L;if (now->R) Q[save ++] = now->R;}while (count)printf("%c",output[-- count]);printf("\n");}int main(){int t;while (~scanf("%d",&t))while (t --) {scanf("%s",Str);TreeSize = 0;memset(Node, 0, sizeof(Node));Now = strlen(Str);bfs(madetree());}    return 0;}


0 0
原创粉丝点击