新的展开 - 从这里开始吧! -- 广度,深度优先遍历是什么?

See the Pen sfgg1 by ukyozq (@deadzq) on CodePen.

var tree = {
  name: 'root',
  children:[{
    name: 'child1',
    children:[{
      name:'child1_1',
      children:[]
    },{name:'child1_2',children:[]}]
  },{
    name:'child2',
    children:[{
      name:'child2_1',
      children:[]
    }]
  },{
    name:'child3',
    children:[{
      name:'child2_1',
      children:[]
    }]
  }]
};

//广度优先遍历:
function wideTraversal(node){
  var nodes = [];
  if(node!=null){
    var queue = [];
    queue.unshift(node);
    while(queue.length!=0){
      var item = queue.shift();
      nodes.push(item.name);
      var children = item.children;
      for(var i=0;i<children.length;i++){
        queue.push(children[i]);
      }
    }
  }
  return nodes;
}
console.log("广度优先遍历:");
console.log(wideTraversal(tree));




//深度优先遍历:
function traverseTree(node){
  var child = node.children,
      arr = [];
  
  arr.push(node.name);
  if(child){
    child.forEach(function(node){
      arr = arr.concat(traverseTree(node));
    });
  }
  return arr;
}
console.log("深度优先遍历:");
console.log(traverseTree(tree));

 

posted @ 2019-03-13 22:30 wizard_Q 阅读(...) 评论(...) 编辑 收藏