树结构根据子节点返回相应父节点树结构?

假设树结构如下:

tree = [
        {
          id: 1,
          label: '节点-1',
          child: [
            {
              id: 2,
              label: '节点-2',
              child: [
                {
                  id: 3,
                  label: '节点-3',
                  child: [
                    {
                      id: 6,
                      label: '节点-6'
                    }
                  ],
                }
              ]
            },
            {
              id: 4,
              label: '节点-4',
              child: [
                {
                  id: 5,
                  label: '节点-5',
                  child: [
                    {
                      id: 7,
                      label: '节点-7'
                    }
                  ],
                }
              ]
            },
          ]
        }
      ]

我想找出id === 7的所有父节点,并且也是树结构形式,请教各位大佬!

阅读 1.8k
1 个回答

用递归来找就行了:

function findParentNode(tree, targetId) {
  if (!tree || !Array.isArray(tree)) return null;

  for (let node of tree) {
    if (node.id === targetId) {
      return [node];
    }

    if (node.child) {
      const path = findParentNode(node.child, targetId);
      if (path) {
        return [{ id: node.id, label: node.label, child: path }];
      }
    }
  }

  return null;
}

const tree = [
  // ...
];

const result = findParentNode(tree, 7);
console.log(result);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题