广度与深度遍历

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div id="d1">
    <div id="d2">
      <div class="cc1"></div>
      <div class="cc5"></div>
    </div>
    <div class="cc3">
      <div class="cc4"></div>
    </div>
  </div>
  <div id="d3">
    <div id="d4"></div>
    <div id="d5">
      <di id="d6"></di>
    </div>
  </div>
  <span id="s1">
    <a id="a1" href=""></a>
  </span>
</body>

<script>
  //深度优先遍历
  function dfc(root) {
    if (root == null) return []
    let result = []
    let nodeStack = []
    nodeStack.push(root)

    while (nodeStack.length > 0) {
      let n = nodeStack.pop()
      result.push(n)
      //反向进栈
      if (n.children) {
        nodeStack.push(...Array.from(n.children).reverse())//DOM元素的children并不是数组类型,先转成数组
      }
    }
    return result
  }


  //广度优先   同一个维度从上到下,从左到右遍历完()
  function bfc(root) {
    if (root == null) return []
    let result = []
    let nodeQueue = []//队列先进先出
    nodeQueue.push(root)

    while (nodeQueue.length > 0) {
      let n = nodeQueue.shift()
      result.push(n)
      if (n.children) {
        nodeQueue.push(...n.children)
      }
    }
    return result
  }

  //广度优先   这种比较好理解一点
  function guanduyouxian(root) {
    if (root == null) return []
    let result = [root]
    for (let i = 0; i < result.length; i++) {
      if (result[i].children) {
        result.push(...result[i].children)
      }
    }
    return result
  }

  //深度优先遍历
  function shendu(root, result = []) {
    result.push(root)
    if(root.children) {
      Array.from(root.children).forEach(item => {
        shendu(item, result)
      });
    }
    return result
  }

  console.log(guanduyouxian(document.body));
  console.log(bfc(document.body));
  console.log(dfc(document.body));
  console.log(shendu(document.body));


</script>

</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值