Javascript版的二叉树

代码如下:

class Node {
  constructor(data){
    this.left = null
    this.right = null
    this.value = data
  }
}

class BinarySearchTree {
  // class BST {
constructor() {
this.root = null;

}
    insertNode(root, newNode){
    if(newNode.value < root.value){
      (!root.left) ? root.left = newNode : this.insertNode(root.left, newNode)
    } else {
      (!root.right) ? root.right = newNode : this.insertNode(root.right, newNode)
    }
  }

  insert(value) {
    let newNode = new Node(value)
    if(!this.root){
      this.root = newNode
    } else {
      this.insertNode(this.root, newNode)
    }
  }

  removeNode(root, value){
    if(!root){
      return null
    }

    if(value < root.value){
      root.left = this.removeNode(root.left, value)
      return root
    } else if(value > root.value){
      root.right = this.removeNode(root.right, value)
      return root
    } else {
      if(!root.left && !root.right){
        root = null
        return root
      }

      else if(root.left && !root.right){
        root = root.left
        return root
      }

      else if(!root.left && root.right){
        root = root.right
        return root
      }

      let minRight = this.findMinNode(root.right)
      root.value = minRight.value
      root.right = this.removeNode(root.right, minRight.value)
      return root
    }
  }

  remove(value){
    if(this.root){
      this.removeNode(this.root, value)
    }
  }

  findMinNode(root) {
    if(!root.left){
      return root
    } else {
      return this.findMinNode(root.left)
    }
  }

  searchNode(root, value) {
    if(!root){
      return null
    }

    if(value < root.value){
      return this.searchNode(root.left, value)
    } else if(value > root.value){
      return this.searchNode(root.right, value)
    }

    return root
  }

  search(value){
    if(!this.root){
      return false
    }
    return Boolean(this.searchNode(this.root, value)) 
  }

  preOrder(root){
    if(root){
      console.log(root.value)
      this.preOrder(root.left)
      this.preOrder(root.right)
    }
  }

  inOrder(root){
    if(root){
      this.inOrder(root.left)
      this.inOrder(root.right)
    }
  }

  postOrder(root){
    if(root){
      this.postOrder(root.left)
      this.postOrder(root.right)
    }
  }
}


let BTS = new BinarySearchTree()

BTS.insert(9)
BTS.insert(7)
BTS.insert(23)

console.log(BTS)

// BinarySearchTree {
// root: Node {
//    left: Node { left: null, right: null, value: 7 },
//    right: Node { left: null, right: null, value: 23 },
//    value: 9
//  }
//}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值