• 请不要在回答技术问题时复制粘贴 AI 生成的内容
ZeroShiro
V2EX  ›  程序员

问个 js 算法题

  •  
  •   ZeroShiro · Feb 21, 2022 · 2672 views
    This topic created in 1718 days ago, the information mentioned may be changed or developed.
    const treeData = [
      {
        id: 1,
        children: {
          id: 2,
          children: {
            id: 3
          }
        }
      },
      {
        id: 4,
        children: {
          id: 5,
          children: {
            id: 6
          }
        }
      }
    ]
    

    // 2 1-2-3 1 1-2-3 3 1-2-3 结构给个 ID 输出上下级

    hello2090
    hello2090
    Feb 21, 2022❤️2
    1
    虽然我 leetcode 刷了 500 多题,但我真看不太懂这题的意思。。
    murmur
    murmur
    Feb 21, 2022
    2
    你的 children 不能带一个指针指向 parent 么
    wenzichel
    wenzichel
    Feb 21, 2022
    3
    只能遍历了吧
    cxe2v
    cxe2v
    Feb 21, 2022
    4
    有点像链表
    Kasumi20
    Kasumi20
    Feb 21, 2022
    5
    function findIndex(id) {
    try {
    treeData.forEach((item, index) => {
    var child = item;
    while (true) {
    if (child.id === id) {
    throw index;
    }
    if (typeof child.children !== 'object') {
    break;
    }
    child = child.children;
    }
    });
    } catch (index) {
    return index;
    }
    return -1;
    }

    function getStruct(index) {
    var child = treeData[index];
    var ids = [];
    while (true) {
    if (typeof child.id === 'number') {
    ids.push(child.id);
    }
    if (typeof child.children !== 'object') {
    break;
    }
    child = child.children;
    }
    return ids;
    }

    function test(id) {
    var index = findIndex(id);
    var ids = getStruct(index);
    console.log(id + ' ' + ids.join('-'));
    }

    test(1);
    test(2);
    test(6);

    /*
    1 1-2-3
    2 1-2-3
    6 4-5-6
    */
    chairuosen
    chairuosen
    Feb 21, 2022
    6
    这结构不是 tree 这是两根电线杆啊
    aikilan
    aikilan
    Feb 21, 2022
    7
    遍历递归,谈不上算法,简单暴力,毫无意义
    nowgoo
    nowgoo
    Feb 21, 2022
    8
    投机一下

    const output = function(treeData, n){
    let flat = e => e.children ? e.id + "-" + flat(e.children) : e.id,
    flatted = treeData.map(flat).map(e => "-"+ e +"-").join(',');
    return flatted.match(new RegExp('[^,]*-'+ n +'-[^,]*'))[0]
    .replace(/^-+/, '')
    .replace(/-+$/, '');
    }
    jguo
    jguo
    Feb 21, 2022
    9
    你这算哪门子 children
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   4583 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 09:33 · PVG 17:33 · LAX 01:33 · JFK 04:33
    ♥ Do have faith in what you're doing.