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

6yjfywim  于 2023-08-08  发布在  Java
关注(0)|答案(3)|浏览(108)

我试图弄清楚如何在这个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);
};

wztqucjr

wztqucjr1#

您的代码只是缺少一个循环来检查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引擎的参数大小溢出,所以对大规模的子数组使用显式循环):

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了。

o4tp2gmn

o4tp2gmn2#

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
  )


相关recursive search using higher-order functions

fnvucqvd

fnvucqvd3#

下面是使用object-scan的解决方案

// const objectScan = require('object-scan');

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":[]}]}]};

const search = (obj, id) => objectScan(['**.id'], {
  abort: true,
  filterFn: ({ value, parent, context }) => {
    if (value === id) {
      context.push(parent.label);
      return true;
    }
    return false;
  }
})(obj, [])[0];

console.log(search(tree, 1));
// => A
console.log(search(tree, 6));
// => F
console.log(search(tree, 99));
// => undefined
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan@13.7.1"></script>

相关问题