现给出扩展二叉树(‘ . ’表示子树为空)的前序序列,要求输出其前中后序序列。
input: ABD..EF..G..C..
//#include<bits/stdc++.h> #include<cstdio> #include<iostream> #include<cstring> #include<string> #include<algorithm> #include<vector> #include<set> #include<cmath> #include<map> #include<queue> using namespace std; #define ll long long #define ull unsigned long long inline ll gcd(ll a, ll b) { return a == 0 ? b : gcd(b % a, a); } inline ll lcm(ll a, ll b) { return (a * b) / gcd(a, b); } inline ll rd() { ll x = 0, f = 1; char ch = getchar(); while (ch<'0' || ch>'9') { if (ch == '-')f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = (x << 3) + (x << 1) + (ch ^ 48); ch = getchar(); } return x * f; } const int maxn = 1e3 + 10; const int mod = 1e9 + 7; typedef struct treepoint * T; struct treepoint { char date; T lson, rson; }; char s[110]; int pos ,len; T build() {//建立二叉树 T bt = (T)malloc(sizeof(treepoint)); pos++; if (s[pos] == '.')bt = NULL; else { bt->date = s[pos]; bt->lson = build(); bt->rson = build(); } return bt; } void pre_order_travel(T bt) {//前序遍历 printf("%c", bt->date); if (bt->lson != NULL) pre_order_travel(bt->lson); if (bt->rson != NULL) pre_order_travel(bt->rson); //free(bt); } void mid_order_travel(T bt){//中序遍历 if (bt->lson != NULL) mid_order_travel(bt->lson); printf("%c", bt->date); if (bt->rson != NULL) mid_order_travel(bt->rson); //free(bt); } void post_order_travel(T bt) {//后序遍历 if (bt->lson != NULL) post_order_travel(bt->lson); if (bt->rson != NULL) post_order_travel(bt->rson); printf("%c", bt->date); //free(bt); } int main() { while (~scanf("%s", s + 1)) { T root = (T)malloc(sizeof(treepoint)); len = strlen(s + 1); pos = 0; root=build(); pre_order_travel(root); puts(""); mid_order_travel(root); puts(""); post_order_travel(root); puts(""); } }