js创建平衡二叉树(AVL)和搜索二叉树(BST)

class tree {
      constructor (val) {
        this.val = val
        this.left = this.right = null
      }
    }

 搜索二叉树:

class BST {
      constructor (data) {
        let len = data.length, i, root
        for (i = 0; i < len; i++) {
          let node = new tree(data[i])
          if (!root) {
            root = node
          } else {
            this.insertBST(root, node)
          }
        }
        return root
      }

      insertBST(root, node) {
        if (root.val > node.val) {
          if (root.left === null) {
            root.left = node
          } else {
            this.insertBST(root.left, node)
          }
        } else {
          if (root.right === null) {
            root.right = node
          } else {
            this.insertBST(root.right, node)
          }
        }
      }
    }

平衡二叉树:

class AVL {
      constructor (data) {
        let len = data.length, nodelist = [], i, root
        for (i = 0; i < len; i++) {
          let node = new tree(data[i])
          nodelist.push(node)
          if (i > 0) {
            let level = Math.floor(Math.sqrt(i+1))
            let levels = Math.pow(2, level) - 1
            let levelups = Math.pow(2, level - 1) - 1
            let parent = nodelist[levelups + Math.floor((i - levels) / 2)]
            if (parent.left) {
              parent.right = node
            } else {
              parent.left = node
            }
          }
        }
        root = nodelist.shift()
        nodelist.length = 0
        return root
      }
    }
发布了18 篇原创文章 · 获赞 3 · 访问量 821

猜你喜欢

转载自blog.csdn.net/qq_16049879/article/details/88865278