文章

17

粉丝

0

获赞

119

访问

4.6k

头像
二叉树遍历2 题解:
P1401 华中科技大学/中国科学院机试题
发布于2025年3月4日 22:08
阅读数 267

#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...

登录查看完整内容


登录后发布评论

暂无评论,来抢沙发