数据结构笔记

81 阅读1分钟

深度优先与广度优先 利用栈与队列构造 以下是js代码

  • 二者相同都以栈\队列判空停止循环
  • 栈以栈顶出站作为参数进行判断
  • 队列以出队作为循环参数进行判断
  • 栈先判断右孩子在判断左孩子
  • 队列与其相反
 bfs() {
    const queue = []
    queue.push(this.root)
    while (queue.length > 0) {
      let current = queue.shift()
      console.log(current.value);
      if (current.left) {
        queue.push(current.left)
      }
      if (current.right) {
        queue.push(current.right)
      }
    }
  }
  dfs() {
    let stack = []
    stack.push(this.root)
    while (stack.length) {
      const node = stack.pop()
      console.log(node.value);
      if (node.right) {
        stack.push(node.right)
      }
      if (node.left) {
        stack.push(node.left)
      }
    }
  }