算法:深度优先遍历与广度优先遍历(代码实现)

json数据

     const json = [
        {
          key: 'A1',
          children: [
            {
              key: 'B1',
              children: [
                { key: 'C1', children: [] },
                { key: 'C2', children: [] },
              ]
            },
            {
              key: 'B2',
              children: []
            },
          ]
        }
      ]

深度优先遍历

     const deepLoop = (jsonTest) => {
        jsonTest.forEach(item => {
          doWork(item)
          if (item.children?.length>0) {
            deepLoop(item.children)
          }
        })
      }

      const doWork = (itemObj) => {
        console.log(itemObj.key) // A1,B1,C1,C2,B2
      }

广度优先遍历

const rangeLoop = (jsonTest) => {
     let jsonList = jsonTest
     for (let i = 0; i < jsonList.length; i++) {
          const item = jsonList[i];
          doWork(item)
          jsonList = jsonList.concat(item.children)
          
    }
}

const doWork = (itemObj) => {
    console.log(itemObj.key) // A1,B1,B2,C1,C2
}

你可能感兴趣的:(javascript,前端)