账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    为什么这样写的循环比递归花费时间长很多呢
    33
    0

    写了一个二叉树,然后分别使用广度遍历和深度遍历,为什么广度遍历比深度遍历用的时间长很多呢?
    遍历的次数是相同的。
    初学算法,请各位指教

    class Node {
      constructor (data, left, right) {
        this.data = data
        this.left = left
        this.right = right
      }
    }
    
    class BST {
      constructor() {
        this.root = null
        this.ordered = []
        this.times = 0
      }
    
      insert (data) {
        var node = new Node(data, null, null)
        if (this.root === null) {
          this.root = node
        } else {
          var current = this.root
          var parent
          while(current !== null) {
            parent = current
            if (data < current.data) {
              current = current.left
            } else if (data > current.data){
              current = current.right
            } else {
              return
            }
          }
          data < parent.data ? (parent.left = node) : (parent.right = node)
        }
      }
    
      inOrder(node) {
        if (node !== null) {
          this.times++
          this.inOrder(node.left)
          this.ordered.push(node.data)
          this.inOrder(node.right)
        }
      }
    
      // 广度优先遍历
      bfs() {
        var arr = []
        arr.push(this.root)
        while(arr.length) {
          this.times++
          var node = arr.shift()
          this.ordered.push(node.data)
          if (node.left) {
            arr.push(node.left)
          }
          if (node.right) {
            arr.push(node.right)
          }
        }
      }
    }
    // test 
    var nums = new BST();
    for (var j = 0; j < 100000; j++) {
      nums.insert(Math.floor(Math.random()*100000))
    }
    
    console.time('bfs')
    nums.bfs()
    console.timeEnd('bfs')
    console.log(nums.times)
    nums.ordered.length = 0
    nums.times = 0
    
    console.time('inorder')
    nums.inOrder(nums.root);
    console.timeEnd('inorder')
    console.log(nums.times)
    2
    打赏
    收藏
    点击回答
    您的回答被采纳后将获得:提问者悬赏的 11 元积分
        全部回答
    • 0
    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部