js对树的广度优先遍历和深度优先遍历

1 篇文章 0 订阅

如下图一棵树:

广度优先遍历顺序:ABCDEFGHIJKLMN

深度优先遍历顺序:ABEFJLMNGCDHKI

广度优先遍历借助于队列,队列的特点是先进先出,后进后出。步骤如下:

1.将A放入队列,将A弹出队列;

2.将A的子节点BCD顺序放入队列(此时B在队头),将B弹出队列,判断B是否有子节点,若有则将B的子节点放入队列,若没有将队列头部元素继续弹出队列(上图B有EFG三个子节点,所以将EFG顺序放入,然后将C弹出队列),继续判断弹出节点是否有子元素,重复此步骤直到队列为空。

深度优先遍历借助于栈,栈的特点是先进后出,后进先出。步骤如下:

1.将A放入栈,将A出栈;

2.将A的子节点BCD倒序入栈(此时B在栈的顶端),将B出栈,判断B是否有子节点,若有则将B的子节点入栈,若没有将队列头部元素继续出栈(上图B有EFG三个子节点,所以将EFG倒序入栈,此时E在栈的顶端,所有将E出栈),继续判断出栈节点是否有子元素,重复此步骤直到栈为空。

代码如下:

class Stack {
  constructor(data = []) {
    this.data = Array.from(data)
  }
  push(v) {
    return this.data.push(v)
  }
  pop() {
    return this.data.pop()
  }
}

class Queue {
  constructor(data = []) {
    this.data = Array.from(data)
  }
  push(v) {
    return this.data.push(v)
  }
  pop() {
    return this.data.shift()
  }
}

class Tree {
  constructor(data = []) {
    this.data = Array.from(data)
    this.queue = new Queue()
    this.stack = new Stack()
  }
  // 广度优先
  printBFS() {
    this.bfs(this.data)
  }
  bfs(data) {
    data.forEach((item) => {
      this.queue.push(item)
    })
    this.bfsFn()
  }

  bfsFn() {
    if (this.queue.data.length === 0) return
    const popV = this.queue.pop()
    console.log(popV.value)
    if (popV.children) {
      this.bfs(popV.children)
    } else {
      this.bfsFn()
    }
  }
  // 深度优先
  printDFS() {
    this.dfs(this.data)
  }
  dfs(data) {
    // 倒序将子节点压入栈中
    for (let i = data.length - 1; i >= 0; i--) {
      this.stack.push(data[i])
    }
    this.dfsFn()
  }
  dfsFn() {
    if (this.stack.data.length === 0) return
    const popV = this.stack.pop()
    console.log(popV.value)
    if (popV.children) {
      this.dfs(popV.children)
    } else {
      this.dfsFn()
    }
  }
}
const tree = new Tree([
  {
    value: 'A',
    children: [
      {
        value: 'B',
        children: [
          {
            value: 'E',
          },
          {
            value: 'F',
            children: [
              {
                value: 'J',
                children: [
                  {
                    value: 'L',
                  },
                  {
                    value: 'M',
                  },
                  {
                    value: 'N',
                  },
                ],
              },
            ],
          },
          {
            value: 'G',
          },
        ],
      },
      {
        value: 'C',
      },
      {
        value: 'D',
        children: [
          {
            value: 'H',
            children: [
              {
                value: 'K',
              },
            ],
          },
          {
            value: 'I',
          },
        ],
      },
    ],
  },
])
console.log('广度优先遍历:')
tree.printBFS()
console.log('深度优先遍历:')
tree.printDFS()

如有错误,欢迎大家指正

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是JavaScript树的深度优先遍历广度优先遍历算法的实现: ```javascript // 定义树节点 class TreeNode { constructor(val) { this.val = val; this.left = null; this.right = null; } } // 深度优先遍历(递归) function dfs(root) { if (!root) return; console.log(root.val); dfs(root.left); dfs(root.right); } // 深度优先遍历(非递归) function dfs2(root) { if (!root) return; const stack = [root]; while (stack.length) { const node = stack.pop(); console.log(node.val); if (node.right) stack.push(node.right); if (node.left) stack.push(node.left); } } // 广度优先遍历 function bfs(root) { if (!root) return; const queue = [root]; while (queue.length) { const node = queue.shift(); console.log(node.val); if (node.left) queue.push(node.left); if (node.right) queue.push(node.right); } } // 创建一棵树 const root = new TreeNode(1); root.left = new TreeNode(2); root.right = new TreeNode(3); root.left.left = new TreeNode(4); root.left.right = new TreeNode(5); root.right.left = new TreeNode(6); root.right.right = new TreeNode(7); // 深度优先遍历 dfs(root); // 输出:1 2 4 5 3 6 7 // 深度优先遍历(非递归) dfs2(root); // 输出:1 3 7 6 2 5 4 // 广度优先遍历 bfs(root); // 输出:1 2 3 4 5 6 7 ``` 以下是以邻接表为存储结构,实现连通无向图的深度优先和广度优先遍历的实现: ```python # 定义图节点 class GraphNode: def __init__(self, val): self.val = val self.neighbors = [] # 深度优先遍历 def dfs(node): if not node: return visited = set() stack = [node] while stack: cur = stack.pop() if cur not in visited: visited.add(cur) print(cur.val) for neighbor in cur.neighbors: stack.append(neighbor) # 广度优先遍历 def bfs(node): if not node: return visited = set() queue = [node] while queue: cur = queue.pop(0) if cur not in visited: visited.add(cur) print(cur.val) for neighbor in cur.neighbors: queue.append(neighbor) # 创建一个图 node1 = GraphNode(1) node2 = GraphNode(2) node3 = GraphNode(3) node4 = GraphNode(4) node5 = GraphNode(5) node6 = GraphNode(6) node1.neighbors = [node2, node3] node2.neighbors = [node1, node4, node5] node3.neighbors = [node1, node6] node4.neighbors = [node2] node5.neighbors = [node2, node6] node6.neighbors = [node3, node5] # 深度优先遍历 dfs(node1) # 输出:1 3 6 5 2 4 # 广度优先遍历 bfs(node1) # 输出:1 2 3 4 5 6 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值