二叉树实现

今天实现一下二叉树
/**
  * 二叉树
  * 二叉链表
  */
 function Node(data){
     this.data = data
     this.left = null
     this.right = null
 }
 
 class Bst {
     constructor(){
         this.root = null
     }
     
     /**
      * 首先创建一个节点,判断是否有根节点
      *  根据值的大小往左右节点查找,直到找到空节点(null)为止
      *  这个新的节点就插在这个空节点的位置
      */
     insert(data){
         let newNode = new Node(data)
         if(this.root === null){
             this.root = newNode
         }else{
             let current = this.root
             let parent
             /**从根节点向下查到,找到空节点 为止, 得到parent */
             while(current){
                 parent = current
                 if(data < current.data){
                     current = current.left
                 }else{
                     current = current.right
                 }
             }
             // 通过上面找到的parent和 新值做对比,决定放在左还是右
             if(data < parent.data){
                 parent.left = newNode
             }else{
                 parent.right = newNode
             }
         }
     }
     // 查找最小值,即在左边树查找, 最大值则相反
     min(){
         if(this.root == null) return null
         let current = this.root
         while(current.left !== null){
             current = current.left
         }
         return current.data
     }

     find(data){
         let current = this.root
         while(current !== null){
             if(current.data == data){
                 return current
             }
             if(current.data > data){
                 current = current.left
             }else{
                 current = current.right
             }
         }
         return null
     }
 }
 // 遍历 ,更加根节点的遍历循序
 function preOrder(node){
     if(node === null) return
     if(typeof node == 'undefined'){
        node = this.root;
     }
     console.log(node.data)
     preOrder(node.left)
     preOrder(node.right)
 }
 function midOrder(node){
    if(node === null) return
    if(typeof node == 'undefined'){
       node = this.root;
    }
     midOrder(node.left)
     console.log(node.data)
     midOrder(node.right)
 }
 function backOrder(node){
    if(node === null) return
    if(typeof node == 'undefined'){
       node = this.root;
    }
    backOrder(node.left)
    backOrder(node.right)
    console.log(node.data)
 }

 
 let a = new Bst()
 a.insert(11);
a.insert(3);
a.insert(5);
a.insert(1);
//  console.log(a,a.root, a.left, a.right)
 console.log(preOrder(a.root))
 console.log(midOrder(a.root))
 console.log(backOrder(a.root))
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容