就是前序中序建树。
//9:26 ~
#include<bits/stdc++.h>
using namespace std;
vector<int> pre, in, ans;
int st[31], pos = -1;
struct node {
int val;
node *lc, *rc;
};
node *bulid (int preL, int preR, int inL, int inR) {
if (preL > preR) return NULL;
node *root = new node();
root->val = pre[preL];
int k = inL;
while (in[k] != pre[preL]) k++;
int left = k - inL;
root->lc = bulid (preL + 1, preL + left, inL, k - 1);
root->rc = bulid (preL + left + 1, preR, k + 1, inR);
return root;
}
void post(node *root) {
if (root == NULL) return;
post(root->lc);
post(root->rc);
ans.push_back(root->val);
}
int main() {
int n, a;
string s;
cin >> n;
for (int i = 0; i < 2 * n; i++) {
cin >> s;
if (s == "Pop") {
in.push_back(st[pos--]);
continue;
}
else {
cin >> a;
pre.push_back(a);
st[++pos] = a;
}
}
node *root = NULL;
root = bulid (0, n - 1, 0, n - 1);
post(root);
for (int i = 0; i < ans.size(); i++) {
if (i != 0) printf (" ");
printf ("%d", ans[i]);
}
}
这篇博客介绍了如何通过前序遍历和中序遍历的序列来构建二叉树。代码实现了一个从输入序列构建二叉树的函数,并通过后序遍历来验证构建结果。主要内容涉及二叉树的遍历和构造算法。
118

被折叠的 条评论
为什么被折叠?



