二叉樹實(shí)現(xiàn)

今天實(shí)現(xiàn)一下二叉樹
/**
  * 二叉樹
  * 二叉鏈表
  */
 function Node(data){
     this.data = data
     this.left = null
     this.right = null
 }
 
 class Bst {
     constructor(){
         this.root = null
     }
     
     /**
      * 首先創(chuàng)建一個(gè)節(jié)點(diǎn),判斷是否有根節(jié)點(diǎn)
      *  根據(jù)值的大小往左右節(jié)點(diǎn)查找,直到找到空節(jié)點(diǎn)(null)為止
      *  這個(gè)新的節(jié)點(diǎn)就插在這個(gè)空節(jié)點(diǎn)的位置
      */
     insert(data){
         let newNode = new Node(data)
         if(this.root === null){
             this.root = newNode
         }else{
             let current = this.root
             let parent
             /**從根節(jié)點(diǎn)向下查到,找到空節(jié)點(diǎn) 為止, 得到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
     }
 }
 // 遍歷 ,更加根節(jié)點(diǎn)的遍歷循序
 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))
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容