美文网首页
广度优先遍历和深度优先遍历

广度优先遍历和深度优先遍历

作者: 沉默紀哖呮肯伱酔 | 来源:发表于2021-05-18 15:34 被阅读0次

    深度优先遍历

    // 递归
    function deepTraversal(node, list = []){
        if(!node) return list;
        list.push(node);
        const children = node.children || [];
        children.map(item => deepTraversal(item, list));
        return list
    }
    // 非递归
    function deepTraversal(node){
      if(!node) return []
      const stack = [node]
      const result = []
      while(!!stack.length){
         const item = stack.pop();
         result.push(item)
         const children = item.children || [];
         for(let i = children.length - 1; i >= 0; i--){
              stack.push(children[i])
         }
      }
    return result
    }
    

    广度优先遍历

    // 非递归
    function widthTraversal(node){
      if(!node) return []
      const stack = [node]
      const result = []
      while(!!stack.length){
         const item = stack.shift();
         result.push(item)
         const children = item.children || [];
         for(let i = 0; i <children.length; i++){
              stack.push(children[i])
         }
      }
    return result
    }
    

    相关文章

      网友评论

          本文标题:广度优先遍历和深度优先遍历

          本文链接:https://www.haomeiwen.com/subject/jpxyjltx.html