分析
前序:根左右
后序:左右根
建树的核心在于理清楚左右各部分有多少
yes的情形:在叶结点,某一块3个时,此时就是唯一情况
no的情形:在叶结点,某一块2个时,无法判断是左边还是右边,此时就会出现2种情况
代码
#include <bits/stdc++.h>
using namespace std;
int quantity, x;
bool flag{ true }, first{ true };
vector<int>preorder, postorder;
struct Tree {
int key;
Tree* lchild, * rchild;
Tree(int x) {
key = x;
lchild = rchild = NULL;
}
};
void InPut();
Tree* BuildTree(Tree*, int, int, int, int);
void WalkPrint(Tree*);
int main() {
InPut();
Tree* root = NULL;
root = BuildTree(root, 0, quantity - 1, 0, quantity - 1);
flag ? printf("Yes\n") : printf("No\n");
WalkPrint(root);
printf("\n");
return 0;
}
void InPut() {
scanf("%d", &quantity);
preorder.resize(quantity);
postorder.resize(quantity);
for (int i = 0; i < quantity; i++) {
scanf("%d", &x);
preorder[i] = x;
}
for (int i = 0; i < quantity; i++) {
scanf("%d", &x);
postorder[i] = x;
}
}
Tree* BuildTree(Tree* T, int pre_begin, int pre_end, int post_begin, int post_end) {
if (pre_end >= pre_begin ) {
T = new Tree(preorder[pre_begin]);
if (post_end - 1 >= 0) {
int w = find(preorder.begin(), preorder.end(), postorder[post_end - 1]) - preorder.begin();
int p = w - pre_begin - 1;
if (p >= 0) {
T->lchild = BuildTree(T->lchild, pre_begin + 1, pre_begin + p, post_begin, post_begin + p - 1);
T->rchild = BuildTree(T->rchild, pre_begin + p + 1, pre_end, post_begin + p, post_end - 1);
}
}
}
if (pre_end - pre_begin == 1) {
flag = false;
}
return T;
}
void WalkPrint(Tree* T) {
if (T == NULL)
return;
WalkPrint(T->lchild);
first ? printf("%d", T->key), first = false : printf(" %d", T->key);
WalkPrint(T->rchild);
}
后记
这种题,不推荐不建树去搞
因为这种题本意就是让你建树的;
因为如果想让你不建树搞,完全可以在时间和空间上卡你
但显然出题人给足了时间和空间
因此与其费劲心力去思考如何不建树,直接出中序,不如暴力建树遍历
这样错了也能明确一定是建树部分出错,而不会是中序遍历出错
考试还是求稳好