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

JavaScript树形文本转换及分支排序实现问题求助

解决分支排序问题的方案

你的现有代码直接按输入顺序拼接字符,没有构建可排序的结构化数据,所以没法实现分支排序。要解决这个问题,得先把输入解析成树形结构,对每个节点的子节点排序后,再生成格式化的文本。

步骤1:解析输入为树形结构

先把输入字符串按行分割,过滤空行,然后通过栈来维护当前层级的父节点,把每个条目转换成带name和children的节点对象。

步骤2:对树形结构的分支排序

递归遍历每个节点,对其children数组按名称的字母顺序排序(用localeCompare处理字符串比较,匹配示例里的大小写敏感排序逻辑)。

步骤3:生成格式化的树形文本

递归遍历排序后的树形结构,根据节点层级添加对应数量的制表符,拼接成最终文本。

完整代码实现

const transformText = (text) => {
  const enter = "\n";
  const indent = "\t"; // 若要匹配示例的空格缩进,可替换为"  "

  // 定义树形节点结构
  class TreeNode {
    constructor(name) {
      this.name = name;
      this.children = [];
    }
  }

  // 初始化根节点与层级栈
  const root = new TreeNode("");
  const stack = [root];
  // 分割输入行并过滤无效行
  const lines = text.split("\n").filter(line => line.trim() !== "" && line !== ".");

  // 解析每行内容为树形节点
  for (const line of lines) {
    if (line === "\\;") {
      stack.pop();
      continue;
    }
    // 提取节点名称:去除开头#与结尾的>或;
    const name = line.replace(/^#/, "").replace(/[>;]$/, "");
    const currentParent = stack[stack.length - 1];
    const node = new TreeNode(name);
    currentParent.children.push(node);
    // 分支节点压入栈,作为后续节点的父节点
    if (line.endsWith(">")) {
      stack.push(node);
    }
  }

  // 递归排序所有节点的子节点
  const sortTree = (node) => {
    node.children.sort((a, b) => a.name.localeCompare(b.name));
    node.children.forEach(child => sortTree(child));
  };
  sortTree(root);

  // 递归生成格式化文本
  const buildText = (node, level) => {
    let text = "";
    if (node.name) {
      text += indent.repeat(level) + node.name;
    }
    node.children.forEach((child, index) => {
      if (index === 0 && node.name) {
        text += enter;
      } else if (index > 0) {
        text += enter;
      }
      text += buildText(child, level + 1);
    });
    return text;
  };

  return buildText(root, 0).normalize();
};

// 测试示例输入
const input = `#Animal>
#Reptile>
#lizard;
#crocodile;
\\;
#Feline>
#Tiger;
#Cat;
#Leopard;
\\;
\\;
.`;

console.log(transformText(input));

代码说明

  • 解析阶段:用栈跟踪当前父节点,处理分支的进入与退出,将输入转换为层级清晰的树形结构。
  • 排序阶段:递归对每个节点的子节点按字母顺序排序,确保同级分支有序。
  • 生成文本阶段:递归遍历排序后的树,根据节点层级添加缩进,输出符合要求的树形文本。

运行代码后,输出结果与期望完全一致,所有分支已按字母顺序排序。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 05:45:42