文章
17
粉丝
0
获赞
119
访问
4.6k
#include <bits/stdc++.h>
using namespace std;
struct tree {
char val;
tree* left;
tree* right;
tree(char n) : val(n), left(nullptr), right(nullptr) {}
};
// 根据前序和中序遍历构建二叉树
tree* create(const string& pre, const string& in, int startpre, int endpre, int startin, int endin) {
if (startpre > endpre || startin > endin) return nullptr; // 边界条件
tree* root = new tree(pre[startpre]); // 前序遍历的第一个节点是根节点
int p = startin;
while (in[p] != pre[startpre]) p++; // 在中序遍历中找到根节点的位置
int leftSize = p - startin; // 左子树的节点数量
// 递归构建左子树
root->left = create(pre, in, startpre + 1, startpre + leftSize, startin, p - 1);
// 递归构建右子树
root->right = create(pre, in, startpre + leftSize + 1, endpre, p + 1, endin);
return root;
}
// 后序遍历
void post(tree* root) {
&nbs...
登录后发布评论
暂无评论,来抢沙发