JavaScript实现DOM树的深度优先遍历和广度优先遍历


// 深度遍历
function interator(node) {
    console.log(node);
    if (node.children.length) {
        for (var i = 0; i < node.children.length; i++) {
            interator(node.children[i]);
        }
    }
}

// 广度遍历
function interator(node) {

    var arr = [];
    arr.push(node);
    while (arr.length > 0) {
        node = arr.shift();
        console.log(node);
        if (node.children.length) {
            for (var i = 0; i < node.children.length; i++) {
                arr.push(node.children[i]);
            }
        }
    }
}
————————————————

深度优先遍历
// 非递归,首次传入的node值为DOM树中的根元素点,即html
// 调用:deep(document.documentElement)
function deep (node) {
  var res = []; // 存储访问过的节点
  if (node != null) {
    var nodeList = []; // 存储需要被访问的节点
    nodeList.push(node);
    while (nodeList.length > 0) {
      var currentNode = nodeList.pop(); // 当前正在被访问的节点
      res.push(currentNode);
      var childrens = currentNode.children;
      for (var i = childrens.length - 1; i >= 0; i--) {
        nodeList.push(childrens[i]);
      }
    }
  }
  return res;
}

// 使用递归
var res = []; // 存储已经访问过的节点
function deep (node) {
  if (node != null) { // 该节点存在
    res.push(node);
    // 使用childrens变量存储node.children,提升性能,不使用node.children.length,从而不必在for循环遍历时每次都去获取子元素
    for (var i = 0,  childrens = node.children; i < childrens.length; i++) {
      deep(childrens[i]);
    }
  }
  return res;
}

广度优先遍历
// 递归
var res = [];
function wide (node) {
  if (res.indexOf(node) === -1) {
    res.push(node); // 存入根节点
  }
  var childrens = node.children;
  for (var i = 0; i < childrens.length; i++) {
    if (childrens[i] != null) {
      res.push(childrens[i]); // 存入当前节点的所有子元素
    }
  }
  for (var j = 0; j < childrens.length; j++) {
    wide(childrens[j]); // 对每个子元素递归
  }
  return res;
}

// 非递归
function wide (node) {
  var res = [];
  var nodeList = []; // 存储需要被访问的节点
  nodeList.push(node);
  while (nodeList.length > 0) {
    var currentNode = nodeList.shift(0);
    res.push(currentNode);
    for (var i = 0, childrens = currentNode.children; i < childrens.length; i++) {
      nodeList.push(childrens[i]);
    }   
  }
  return res;
}
 

————————————————
版权声明:本文为CSDN博主「qinchao888」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/GreyBearChao/article/details/82872441

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值