JavaScript 中嵌套对象结构中的递归树搜索

新手上路,请多包涵

我试图弄清楚如何递归地搜索此 JSON 对象中的节点。我尝试了一些但无法得到它:

 var tree = {
    "id": 1,
    "label": "A",
    "child": [
        {
            "id": 2,
            "label": "B",
            "child": [
                {
                    "id": 5,
                    "label": "E",
                    "child": []
                },
                {
                    "id": 6,
                    "label": "F",
                    "child": []
                },
                {
                    "id": 7,
                    "label": "G",
                    "child": []
                }
            ]
        },
        {
            "id": 3,
            "label": "C",
            "child": []
        },
        {
            "id": 4,
            "label": "D",
            "child": [
                {
                    "id": 8,
                    "label": "H",
                    "child": []
                },
                {
                    "id": 9,
                    "label": "I",
                    "child": []
                }
            ]
        }
    ]
};

这是我的非工作解决方案,这可能是因为第一个节点只是一个值,而子节点在数组中:

 function scan(id, tree) {
    if(tree.id == id) {
        return tree.label;
    }

    if(tree.child == 0) {
        return
    }

    return scan(tree.child);
};

原文由 VladimirCoder84 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 279
2 个回答

您的代码只是缺少一个循环来检查 child 数组中节点的每个子节点。此递归函数将返回节点的 label 属性或 undefined 如果树中不存在标签:

 const search = (tree, target) => {
  if (tree.id === target) {
    return tree.label;
  }

  for (const child of tree.child) {
    const found = search(child, target);

    if (found) {
      return found;
    }
  }
};

const tree = {"id":1,"label":"A","child":[{"id":2,"label":"B","child":[{"id":5,"label":"E","child":[]},{"id":6,"label":"F","child":[]},{"id":7,"label":"G","child":[]}]},{"id":3,"label":"C","child":[]},{"id":4,"label":"D","child":[{"id":8,"label":"H","child":[]},{"id":9,"label":"I","child":[]}]}]};

console.log(search(tree, 1));
console.log(search(tree, 6));
console.log(search(tree, 99));

您也可以使用不会导致堆栈溢出的显式堆栈迭代地执行此操作(但请注意,简写 stack.push(...curr.child); 可能由于扩展语法而溢出某些 JS 引擎的参数大小,因此请使用显式循环或 concat 用于大量子数组):

 const search = (tree, target) => {
  for (const stack = [tree]; stack.length;) {
    const curr = stack.pop();

    if (curr.id === target) {
      return curr.label;
    }

    stack.push(...curr.child);
  }
};

const tree = {"id":1,"label":"A","child":[{"id":2,"label":"B","child":[{"id":5,"label":"E","child":[]},{"id":6,"label":"F","child":[]},{"id":7,"label":"G","child":[]}]},{"id":3,"label":"C","child":[]},{"id":4,"label":"D","child":[{"id":8,"label":"H","child":[]},{"id":9,"label":"I","child":[]}]}]};

for (let i = 0; ++i < 12; console.log(search(tree, i)));

更通用的设计会返回节点本身,并让调用者访问 .label 属性(如果他们愿意),或者以其他方式使用该对象。

请注意,JSON 纯粹是序列化(字符串化、原始)数据的字符串格式。一旦将 JSON 反序列化为 JavaScript 对象结构,就像这里一样,它就不再是 JSON。

原文由 ggorlen 发布,翻译遵循 CC BY-SA 4.0 许可协议

scan 可以使用第三个参数递归编写,该参数模拟要扫描的节点队列

const scan = (id, tree = {}, queue = [ tree ]) =>
  // if id matches node id, return node label
  id === tree.id
    ? tree.label

  // base case: queue is empty
  // id was not found, return false
  : queue.length === 0
    ? false

  // inductive case: at least one node
  // recur on next tree node, append node children to queue
  : scan (id, queue[0], queue.slice(1).concat(queue[0].child))

因为 JavaScript 支持默认参数,所以 scan 的调用站点不变

console.log
  ( scan (1, tree)  // "A"
  , scan (3, tree)  // "C"
  , scan (9, tree)  // "I"
  , scan (99, tree) // false
  )

验证它在下面的浏览器中是否有效

 const scan = (id, tree = {}, queue = [ tree ]) =>
  id === tree.id
    ? tree.label
  : queue.length === 0
    ? false
  : scan (id, queue[0], queue.slice(1).concat(queue[0].child))

const tree =
  { id: 1
  , label: "A"
  , child:
      [ { id: 2
        , label: "B"
        , child:
            [ { id: 5
              , label: "E"
              , child: []
              }
            , { id: 6
              , label: "F"
              , child: []
              }
            , { id: 7
              , label: "G"
              , child: []
              }
            ]
        }
      , { id: 3
        , label: "C"
        , child: []
        }
      , { id: 4
        , label: "D"
        , child:
            [ { id: 8
              , label: "H"
              , child: []
              }
            , { id: 9
              , label: "I"
              , child: []
              }
            ]
        }
      ]
  }

console.log
  ( scan (1, tree)  // "A"
  , scan (3, tree)  // "C"
  , scan (9, tree)  // "I"
  , scan (99, tree) // false
  )

使用高阶函数的相关递归搜索

原文由 Mulan 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏