YZOJ P3643 题解 发表于 2019-02-20 | 阅读次数: 题面:https://fzyzoi.tk/OnlineJudge/problem_show.php?id=3643 主要思路就是建一棵树,然后根据三种遍历的定义写一个函数,再分别输出遍历结果。 Code 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091/* 3 2 3 0 0 0 0*//* 1 2 3 2 1 3 2 3 1*/#include <cstdio>#define maxn 100000int n/*结点数*/, l[maxn + 10]/*左儿子*/, r[maxn + 10]/*右儿子*/;struct tree {/*树的结构体*/ int data; tree *lchild, *rchild;};namespace Lonely { inline int read() { #define in(n) n=read() register int x=0; register char ch = getchar(); for(; ch < '0' || ch > '9'; ch = getchar()); for(; ch >= '0' && ch <= '9'; ch = getchar()) x = (x << 1) + (x << 3) + (ch ^ 48); return x; } inline void write(int x) { #define out(n) write(n) #define outn(n) write(n), putchar('\n') if(x < 0) {putchar('-');x = -x;} if(x >= 10)write(x / 10); putchar(x % 10 + '0'); } tree *ctetree(int i) {/*建树*/ tree *t = NULL; t = new tree(); t -> data = i; if(l[i])t -> lchild = ctetree(l[i]); if(r[i])t -> rchild = ctetree(r[i]); return t; } void pre(tree *root) {/*前序*/ if(root) { out(root -> data), putchar(' '); pre(root -> lchild); pre(root -> rchild); } else return; } void ino(tree *root) {/*中序*/ if(root) { ino(root -> lchild); out(root -> data), putchar(' '); ino(root -> rchild); } else return; } void pos(tree *root) {/*后序*/ if(root) { pos(root -> lchild); pos(root -> rchild); out(root -> data), putchar(' '); } else return; } int Main() {/*分别输出*/ in(n); for(int i = 1; i <= n; i++) in(l[i]), in(r[i]); tree *root = ctetree(1); pre(root); putchar('\n'); ino(root); putchar('\n'); pos(root); return 0; }}int main() { return Lonely::Main();} $\color{gray}{\mathcal{By}}$ $\color{gray}{\mathfrak{NULL}}$