You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于XML提取的父子关系数据构建层级树并生成指定格式输出

实现思路
  • 第一步:构建父子映射表
    遍历你现有的vector<t>结构,将扁平的父子关系转换为父节点对应所有子节点列表的哈希映射,降低后续查找子节点的时间复杂度,示例代码:
#include <unordered_map>
#include <vector>
#include <string>
#include <iostream>

using namespace std;

struct t{
    string p; /* parent */
    string c; /* child, child can be a parent of another node */
};

unordered_map<string, vector<string>> build_child_map(const vector<t>& tree) {
    unordered_map<string, vector<string>> child_map;
    for (const auto& node : tree) {
        child_map[node.p].push_back(node.c);
    }
    return child_map;
}
  • 第二步:递归遍历输出带层级的树结构
    采用深度优先搜索(DFS)遍历,每递归一层就叠加固定长度的缩进,同时携带当前层级参数跟踪节点深度。根节点ROOT层级为0,无缩进也不需要前置>标识,子节点每深一级增加对应长度的缩进,示例代码:
void print_tree(const unordered_map<string, vector<string>>& child_map, const string& current_node, int level) {
    // 输出当前节点
    if (level == 0) {
        // 根节点直接输出
        cout << current_node << endl;
    } else {
        // 非根节点先输出对应层级的缩进,再加 > 和节点名
        // 可调整系数3匹配你示例中的缩进效果
        string indent(3 * (level - 1), ' ');
        cout << indent << " >  " << current_node << endl;
    }
    // 递归遍历所有子节点
    auto it = child_map.find(current_node);
    if (it != child_map.end()) {
        for (const auto& child : it->second) {
            print_tree(child_map, child, level + 1);
        }
    }
}
  • 第三步:调用入口
    直接传入根节点ROOT和初始层级0即可:
int main() {
    // 假设你已经完成了tree变量的填充逻辑
    vector<t> tree;
    // ... 你的tree填充代码 ...
    auto child_map = build_child_map(tree);
    print_tree(child_map, "ROOT", 0);
    return 0;
}

如果你的节点层级极深担心栈溢出,也可以换成迭代版的广度优先搜索(BFS)实现:用队列存储(节点名, 当前层级)的二元组,循环出队输出并将子节点入队即可。如果需要子节点按固定顺序输出,把unordered_map换成map或者保留插入顺序的容器即可。

内容的提问来源于stack exchange,提问作者Kelsye C

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 07:15:02