【问题标题】:How to find a tree inside a tree in typescript如何在打字稿中找到一棵树内的一棵树
【发布时间】:2023-03-17 16:15:01
【问题描述】:

假设我在 javascript 中有一棵树

a1 
--b
----c1
a2
--b2
--b3
----c2

如果我想找到 c2,它应该返回 a2->b3->c2

假设我的 json 看起来像这样?

treeFamily = {
            name : "Parent",
            children: [{
                name : "Child1",
                children: [{
                    name : "Grandchild1",
                    children: []
                },{
                    name : "Grandchild2",
                    children: []
                },{
                    name : "Grandchild3",
                    children: []
                }]
            }, {
                name: "Child2",
                children: []
            }]
        };

【问题讨论】:

    标签: javascript arrays typescript recursion ecmascript-6


    【解决方案1】:

    您可以使用for...of 通过递归调用函数来搜索孩子。如果找到目标,则返回名称,并与之前的名称组合。如果不是,该函数将返回undefined。或者,您可以返回一个空数组。

    const findPath = (targetName, { name, children }) => {
      if(name === targetName) return [name];
      
      for(const child of children) {
        const result = findPath(targetName, child);
        if(result) return [name, ...result];
      }
      
      // if child not found implicitly return undefined or return [] to get an empty array
    };
    
    const treeFamily = { name: "Parent", children: [{ name: "Child1", children: [{ name: "Grandchild1", children: [] }, { name: "Grandchild2", children: [] }, { name: "Grandchild3", children: [] }] }, { name: "Child2", children: [] }] };
    
    console.log(findPath('Child2', treeFamily));
    console.log(findPath('Grandchild3', treeFamily));
    console.log(findPath('Grandchild400', treeFamily));

    【讨论】:

    • 谢谢。我阻塞了几个小时以在我的项目中调整您的算法。我使用了一个 array.ForEach (...) 循环,但仍然再次得到“未定义”,但使用你的“for”循环我的结果是正确的。也许它可以帮助某人。
    【解决方案2】:

    您可以检查嵌套子项是否具有所需的键/值。然后取name 并将结果交给外部调用。

    function findPath(array, target) {
        var path;
        array.some(({ name, children }) => {
            var temp;
            if (name === target) {
                path = [name];
                return true;
            }
            if (temp = findPath(children, target)) {
                path = [name, ...temp];
                return true;
            }
        });
        return path;
    }
    
    var treeFamily = { name: "Parent", children: [{ name: "Child1", children: [{ name: "Grandchild1", children: [] }, { name: "Grandchild2", children: [] }, { name: "Grandchild3", children: [] }] }, { name: "Child2", children: [] }] };
    
    console.log(findPath([treeFamily], 'Grandchild2'));
    console.log(findPath([treeFamily], 'foo'));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多