#include <iostream>
#include <map>
#include <queue>
#include <algorithm>
#include <cstring>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
struct Node
{
char key;
Node *left, *right;
Node(char a): key(a) {
left = right = NULL;
}
};
struct Sub//表示一棵子树的结构体
{
Node *root;//子树的根
int lastid;//子树的最后一个节点在pre序列中的位置
};
char pre[110];
Sub Get(int id, int &noden)//递归构建一棵树
{
if (pre[id] == '#') return {NULL, id};
Node *root = new Node(pre[id]);
noden++;
Sub ans = Get(id + 1, noden);
root->left = ans.root;
ans = Get(ans.lastid + 1, noden);
root->right = ans.root;
return {root, ans.lastid};
}
void In(Node *root, int &noden)//中序遍历一棵树
{
if (root == NULL) return;
In(root->left, noden);
printf("%c", root->key);
noden--;
if (noden != 0) printf(" ");
In(root->right, noden);
return;
}
int main(int argc, char** argv) {
Sub ans;
int noden;//树上的非空节点数
while (scanf("%s", pre) != EOF) {
noden = 0;
ans = Get(0, noden);
In(ans.root, noden);
printf("\n");
}
}
二叉树的左右子树性质使得关于二叉树的很多解法都能够通过递归解决,以树的几种遍历为基础,我们能模仿着设计很多类似算法:对树的左右子树分别执行同样的操作,最后把结果汇总。