数据结构_平衡二叉树

// 节点类
  class Node {
    constructor(data) {
      this.data = data
      this.left = null
      this.right = null
    }
  }
  //平衡二叉树Balanced Binary Tree
  class BBT {
    constructor() {
      this.root = null
    }

    insert(data) {
      // 新建节点
      let newNode = new Node(data)                
      // 插入节点: this.root 是会进行改变
      this.root = this.insertNode(this.root, newNode)
    }
    insertNode(node, newNode) {
      // 当前为空树
      if (node == null) {
        node = newNode
        return node
      } else if (newNode.data < node.data) {
        // 向左边走
        if (node.left == null) {
          node.left = newNode
          return node
        } else {
          node.left = this.insertNode(node.left, newNode)
          // 判断平衡
          node = this.checkIsBalance(node)
        }
      } else if (newNode.data > node.data) {
        // 向右边走
        if (node.right == null) {
          node.right = newNode
          return node
        } else {
          node.right = this.insertNode(node.right, newNode)
          // 判断平衡
          node = this.checkIsBalance(node)
        }
      }
      return node
    }

    checkIsBalance(node) {
      // 根据左右子树的高度
      // 1. 左子树-右子树 > 1
      if ((this.getHeight(node.left) - this.getHeight(node.right)) > 1) {
        if (this.getHeight(node.left.left) > this.getHeight(node.left.right))
          node = this.rotateR(node)// 右旋
        else
          node = this.rotateLR(node)// 先左旋再右旋
      } // 2. 右子树-左子树 > 1
      else if ((this.getHeight(node.right) - this.getHeight(node.left)) > 1) {
        if (this.getHeight(node.right.right) > this.getHeight(node.right.left))
          node = this.rotateL(node)// 左旋
        else
          node = this.rotateRL(node)// 先右旋再左旋
      }
      return node
    }
    // 孩子中最大高度+1
    getHeight(node) {
      if (node == null) return 0
      // 返回当前节点子树中的较大值+1
      // Math.max()
      return (Math.max(this.getHeight(node.left), this.getHeight(node.right))) + 1
    }
    // 右旋
    rotateR(node){
      let temp = node.left
      node.left = temp.right
      temp.right = node
      return temp
    }

    // 左旋
    rotateL(node){
      let temp = node.right
      node.right = temp.left
      temp.left = node
      return temp
    }

    // 左右旋
    rotateLR(node){
      node.left = this.rotateL(node.left)
      return this.rotateR(node)
    }
    // 右左旋
    rotateRL(node){
      node.right = this.rotateR(node.right)
      return this.rotateL(node)
    }
  }

猜你喜欢

转载自www.cnblogs.com/JunLan/p/12359544.html
今日推荐