文章

454

粉丝

0

获赞

1

访问

10.1k

头像
树的子结构 题解(C++ AC 代码)
P5375 复旦大学2023年机试题
发布于 2026年11月
阅读数 9

题意

两棵树用层序序列(null 表示空)给出,判断 B 是否为 A 的子结构。

思路

  • 按层序 token 建树:每个非空节点依次占用后面两个 token 作为左右孩子。

  • 枚举 A 的每个节点作为起点,与 B 的根做同步比较:值相同且左右都匹配。

  • B 走到空节点即视为匹配成功(允许 A 在 B 的叶子下面还有节点)。

复杂度

O(nA * nB) 最坏,实际很快。

参考代码(C++)

C++:

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
using namespace std;

struct Node { int l, r, v; };

static vector<Node> build(const vector<string> &tok) {
    vector<Node> tr;
    if (tok.empty() || tok[0] == "null") return tr;
    Node root; root.l = root.r = -1; root.v = atoi(tok[0].c_str());
    tr.push_back(root);
    vector<int> q; q.push_back(0);
    size_t p = 1;
    for (size_t h = 0; h < q.size(); h++) {
        int u = q[h];
        if (p < tok.size()) {
            if (tok[p] != "null") {
                Node nd; nd.l = nd.r = -1; nd.v = atoi(tok[p].c_str());
                tr.push_back(nd);
                tr[u].l = (int)tr.size() - 1;
                q.push_back((int)tr...
登录查看完整内容


登录后发布评论

暂无评论,来抢沙发